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