1.maven项目在pom.xml中依赖POIjava
<!-- poi add by wjb on 2016-12-20--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.8.2</version> </dependency> <!-- end poi -->
2.建立一个java类,Utils,用于设置表头和表体的单元格格式web
package com.contract.base.util; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFFont; import org.springframework.web.servlet.view.document.AbstractExcelView; public class ExcelUtils { /** * 表头单元格格式 * @param wb * @return */ public static CellStyle getHeadCellStyle(Workbook wb){ CellStyle style = wb.createCellStyle(); //设置水平垂直居中 style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //是否自动换行 style.setWrapText(false); //边框 style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); //设置字体 Font headerFont = wb.createFont(); headerFont.setFontHeightInPoints((short) 12); headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); headerFont.setFontName("宋体"); style.setFont(headerFont); return style; } /** * 表体单元格格式 * @param wb * @return */ public static CellStyle getBodyCellStyle(Workbook wb){ CellStyle style = wb.createCellStyle(); //对齐方式 style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //换行 style.setWrapText(false); //边框 style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); //字体 Font font = wb.getFontAt(style.getFontIndex()); font.setFontHeightInPoints((short) 11); font.setFontName("宋体"); return style; } public static class ExcelView extends AbstractExcelView { @Override public void buildExcelDocument(Map<String, Object> map, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { //获取文件名称,并改为相应的编码 String fileName = map.get("fileName").toString(); // fileName = java.net.URLEncoder.encode(fileName, "UTF-8");//IE 后面有时间再兼容 fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");//火狐&谷歌 //设置响应格式 response.setContentType("application/vnd.ms-excel;charset=utf-8"); 设置响应头 response.setHeader("Content-disposition", "attachment;filename=" + fileName); //获取输出流,并进行输出 OutputStream ouputStream = response.getOutputStream(); workbook.write(ouputStream); ouputStream.flush(); ouputStream.close(); } } }
3.在前台,建立一个临时表单,并给表单设置一个提交路径。提交后清除临时表单spring
var form = $('<form></form>'); // 设置属性 form.attr('action', ctx + "export/exportabc"); form.attr('method', 'post'); // 建立Input var formParam = $('<input type="hidden" name="method" />').val("1"); // 附加到Form form.append(formParam); // 提交表单 form.appendTo(document.body).submit(); //有必要移除动态建立的form form.remove();
4.在后台接受参数 5.若是是导出,定义要导出的表头。和表头对应的字段名称数据库
//表头和字段名称必须一一对应且顺序一致。由于后面要根据字段名称取出该表头对应的数据 String[] headers =new String[2]; String[] fields = new Strign[2];
6.根据导出的要紧,在数据库查询到对应的数据。获取到数据dataList. 7.进行数据处理apache
//建立一个book类 HSSFWorkbook hWorkbook = new HSSFWorkbook(); //生成一个对应的sheet HSSFSheet hSheet = hWorkbook.createSheet(); //设置一个表头 //建立第一行,由于是表头,且计数从0开始 HSSFRow hRow = hSheet.createRow(0); //将表头进行格式设置 CellStyle hStyle = ExcelUtils.getHeadCellStyle(hWorkbook); //填充表头,表里表头数组 for(int i=0; i<xlsHeaders.length; i++ ){ //建立一个单元格 HSSFCell hCell = hRow.createCell(i); //设置一个单元格格式 hCell.setCellStyle(hStyle); //填充一个单元格内容 hCell.setCellValue(xlsHeaders[i]); } //填充内容 if ( ! CollectionUtils.isEmpty(dataList)) { //获取一个表体的格式 CellStyle cStyle = ExcelUtils.getBodyCellStyle(hWorkbook); //遍历数据,由于每一条数据都是Excel表中的一行 for (int i = 0; i < dataList.size(); i++) { //生成第一行,由于已经存在了表头,因此行数+1 HSSFRow hRow = hSheet.createRow(i + 1); //将该行对应的数据转化为map格式,其中key为字段名称,value为字段对应的值。 Map<String, Object> valueMap = BeanUtils.toMap(dataList.get(i)); //遍历表头对应的字段信息tableFields,即为上面的fields数组 for(int j=0;j<tableFields.length;j++){ HSSFCell xCell = hRow.createCell(j); if(xCell == null) continue; xCell.setCellStyle(cStyle); Object valueObj = getValue(valueMap,tableFields[j]); String value_str =( valueObj == null) ? "" : valueObj.toString(); if(StringUtils.isNotBlank(value_str) && codeMap != null && codeMap.containsKey(j)){ value_str = codeMap.get(j).get(value_str); } xCell.setCellValue(value_str); } } } } }
8.数据处理结束后进行建立实体的Excel文件数组
ExcelView.buildExcelDocument(map, workbook, request, response); //map里面存放文件名称等信息 //workbook为数据处理结束后的HSSFWorkbook
9.建立实体后进行响应,响应返回一个ModelAndView new ModelAndView(ExcelView,map);app