工具,以输出流的形式导出excel文件 package com.zhiyou.usermanage.util; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpS
工具,以输出流的形式导出excel文件
package com.zhiyou.usermanage.util; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.joda.time.DateTime; public class ExportExcel { public static void exportXls(List<Map<String,Object>> list,HttpServletResponse response) throws Exception { OutputStream os=response.getOutputStream();//取得输出流 response.reset();//清空输出流 response.setHeader("Content-disposition", "attachment; filename=test.xls");// 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型 HSSFWorkbook workbook = new HSSFWorkbook(); // 创建Excel的sheet HSSFSheet sheet = workbook.createSheet("用户"); sheet.setForceFormulaRecalculation(true); // 根据模板中表达式位置, 修改对应单元格的值 //创建表格头 Map<String, Object> first=list.get(0); HSSFRow header=sheet.createRow(0); int headerColNum=0; for(Entry<String, Object> e:first.entrySet()) { header.createCell(headerColNum).setCellValue(e.getKey()); headerColNum++; } int rowNum = 1; for (Map<String, Object> map : list) { HSSFRow row = sheet.createRow(rowNum); int colNum=0; for (String key : map.keySet()) { if(map.get(key) instanceof Date) { row.createCell(colNum).setCellValue(new DateTime(map.get(key)).toString(Constants.DATE_TIME)); }else { row.createCell(colNum).setCellValue(map.get(key).toString()); } colNum++; } rowNum++; } workbook.write(os); os.close(); } }
其中的Constants类
package com.zhiyou.usermanage.util; public interface Constants { public String DATE = "yyyy-MM-dd"; public String DATE_TIME = "yyyy-MM-dd hh:mm:ss"; }
映射文件,按顺序存放了字段头信息,在导出过程中只需选取第一行的key值写出表格头
<select id="selectExport" resultType="java.util.LinkedHashMap"> select <include refid="Base_Column_List"/> from tb_user </select>