package com.iamberry.wechat.tools;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 * 导入到EXCEL
 * @author Administrator
 */
public class ObjectExcelView extends AbstractExcelView{

	/**
	 * model参数为：
	 * 	fileName: 下载的文件名称
	 * 	titles:  excel的文件标题
	 * 	varList: 文件内容
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		
		// 准备文件名
		Date date = new Date();
		StringBuffer filename = new StringBuffer("iamberry-");
		String modelFileName = model.get("fileName").toString();
		filename.append(DateTimeUtil.format(date, "yyyyMMddHHmmss-")).append(modelFileName == null ? "default" : modelFileName);
		// 工作薄对象
		HSSFSheet sheet;
		HSSFCell cell;
		sheet = workbook.createSheet("iamberry-sheet");
		
		// 设置返回内容
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="+new String((filename.toString()).getBytes("UTF-8"), "ISO-8859-1")+".xls");
		
		// 标题内容
		List<String> titles = (List<String>) model.get("titles");
		int len = titles.size();
		
		// 标题样式
		HSSFCellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		HSSFFont headerFont = workbook.createFont();	//标题字体
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontHeightInPoints((short)11);
		headerStyle.setFont(headerFont);
		short width = 20,height=25*20;
		sheet.setDefaultColumnWidth(width);
		
		// 设置标题
		for(int i=0; i<len; i++){
			String title = titles.get(i);
			cell = getCell(sheet, 0, i);
			cell.setCellStyle(headerStyle);
			setText(cell,title);
		}
		// 标题的高度
		sheet.getRow(0).setHeight(height);
		
		//内容样式
		HSSFCellStyle contentStyle = workbook.createCellStyle();
		contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		
		// 设置内容
		List<List<Object>> varList = (List<List<Object>>) model.get("varList");
		
		int row = 1; // 行数，第一行被标题占据，所以从第二行开始
		for (List<Object> list : varList) {
			
			int col = 0;// 当前行的列数
			for (Object object : list) {
				//			          工作薄对象          行         列
				cell = getCell(sheet, row, col);
				cell.setCellStyle(contentStyle);
				setText(cell,StrUtils.checkStr(object));
				
				col ++; // 列迭代
			}
			
			row ++; // 行迭代
		}
	}

}
