這里主要前面是通過一個全局變量,在layui的done回調里拿到數據,然后將該數據導出到excel,這里要注意一點,下載excel不能用ajax方式,如果采用ajax下載默認會讀取response返回的二進制數據,所以這里采用表單方式提交 數據。
依賴:SSM架構
<!--poi導出數據到excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
前端部分
<form action="/doExport.action" id="download_form" method="post" class="layui-inline" style="display: inline;">
<input type="hidden" id="page_data" class="layui-inline" name="userList">
<input type="button" class="layui-btn layui-btn-normal layui-inline" id="export_excel" value="導出數據"/>
</form>
$('#export_excel').on('click',function () {
$('#page_data').val(JSON.stringify(userPage.data));
$("#download_form").submit();
//$.ajax();
});
服務器端部分
1.Controller層接收數據
@RequestMapping(value = "/doExport") @ResponseBody public void exportExcelData(HttpServletRequest request, HttpServletResponse response, @RequestParam String userList){ List<MgUser> mgUsers = JSONArray.parseArray(userList,MgUser.class); // ReturnResult returnResult = new ReturnResult(); // 定義表的標題 String title = "用戶列表"; //定義表的列名 String[] rowsName = new String[] { "序號", "用戶名", "密碼", "性別", "昵稱", "出生年月" }; //定義表的內容 ExcelUtil excelUtil = new ExcelUtil(); List<Object[]> dataList = new ArrayList<Object[]>(); for (int i=0;i<mgUsers.size();i++){ Object[] objects = new Object[rowsName.length]; objects[0] = mgUsers.get(i).getId(); objects[1] = mgUsers.get(i).getUsername(); objects[2] = mgUsers.get(i).getPassword(); objects[3] = mgUsers.get(i).getGender(); objects[4] = mgUsers.get(i).getNichen(); objects[5] = mgUsers.get(i).getBirthday(); dataList.add(objects); } try { String fileName= new String("用戶數據表.xlsx".getBytes("UTF-8"),"iso-8859-1"); //生成word文件的文件名 excelUtil.exportExcel(title,rowsName,dataList,fileName,response); //returnInfo.setResult(true); }catch (Exception e){ e.printStackTrace(); } }
2.工具類
import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.List; public class ExcelUtil { /** * 導出excel * @param title 導出表的標題 * @param rowsName 導出表的列名 * @param dataList 需要導出的數據 * @param fileName 生成excel文件的文件名 * @param response */ public void exportExcel(String title, String[] rowsName, List<Object[]> dataList, String fileName, HttpServletResponse response) throws Exception{ OutputStream output = response.getOutputStream(); response.reset(); response.setHeader("Content-disposition", "attachment; filename="+fileName); response.setContentType("application/msexcel"); this.export(title,rowsName,dataList,fileName,output); this.close(output); } /* * 導出數據 */ private void export(String title,String[] rowName,List<Object[]> dataList,String fileName,OutputStream out) throws Exception { try { HSSFWorkbook workbook = new HSSFWorkbook(); // 創建工作簿對象 HSSFSheet sheet = workbook.createSheet(title); // 創建工作表 HSSFRow rowm = sheet.createRow(0); // 產生表格標題行 HSSFCell cellTiltle = rowm.createCell(0); //創建表格標題列 // sheet樣式定義; getColumnTopStyle(); getStyle()均為自定義方法 --在下面,可擴展 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 獲取列頭樣式對象 HSSFCellStyle style = this.getStyle(workbook); // 獲取單元格樣式對象 //合並表格標題行,合並列數為列名的長度,第一個0為起始行號,第二個1為終止行號,第三個0為起始列好,第四個參數為終止列號 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1))); cellTiltle.setCellStyle(columnTopStyle); //設置標題行樣式 cellTiltle.setCellValue(title); //設置標題行值 int columnNum = rowName.length; // 定義所需列數 HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置創建行(最頂端的行開始的第二行) // 將列頭設置到sheet的單元格中 for (int n = 0; n < columnNum; n++) { HSSFCell cellRowName = rowRowName.createCell(n); // 創建列頭對應個數的單元格 cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 設置列頭單元格的數據類型 HSSFRichTextString text = new HSSFRichTextString(rowName[n]); cellRowName.setCellValue(text); // 設置列頭單元格的值 cellRowName.setCellStyle(columnTopStyle); // 設置列頭單元格樣式 } // 將查詢出的數據設置到sheet對應的單元格中 for (int i = 0; i < dataList.size(); i++) { Object[] obj = dataList.get(i); // 遍歷每個對象 HSSFRow row = sheet.createRow(i + 3); // 創建所需的行數 for (int j = 0; j < obj.length; j++) { HSSFCell cell = null; // 設置單元格的數據類型 if (j == 0) { cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(i + 1); } else { cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING); if (!"".equals(obj[j]) && obj[j] != null) { cell.setCellValue(obj[j].toString()); // 設置單元格的值 } } cell.setCellStyle(style); // 設置單元格樣式 } } // 讓列寬隨着導出的列長自動適應 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow currentRow; // 當前行未被使用過 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { HSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { int length = currentCell.getStringCellValue() .getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if (colNum == 0) { sheet.setColumnWidth(colNum, (columnWidth - 2) * 256); } else { sheet.setColumnWidth(colNum, (columnWidth + 4) * 256); } } workbook.write(out); } catch (Exception e) { e.printStackTrace(); } } /* * 列頭單元格樣式 */ private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 設置字體 HSSFFont font = workbook.createFont(); // 設置字體大小 font.setFontHeightInPoints((short) 11); // 字體加粗 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 設置字體名字 font.setFontName("Courier New"); // 設置樣式; HSSFCellStyle style = workbook.createCellStyle(); // 設置底邊框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 設置底邊框顏色; style.setBottomBorderColor(HSSFColor.BLACK.index); // 設置左邊框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 設置左邊框顏色; style.setLeftBorderColor(HSSFColor.BLACK.index); // 設置右邊框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); // 設置右邊框顏色; style.setRightBorderColor(HSSFColor.BLACK.index); // 設置頂邊框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); // 設置頂邊框顏色; style.setTopBorderColor(HSSFColor.BLACK.index); // 在樣式用應用設置的字體; style.setFont(font); // 設置自動換行; style.setWrapText(false); // 設置水平對齊的樣式為居中對齊; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 設置垂直對齊的樣式為居中對齊; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } /* * 列數據信息單元格樣式 */ private HSSFCellStyle getStyle(HSSFWorkbook workbook) { // 設置字體 HSSFFont font = workbook.createFont(); // 設置字體大小 // font.setFontHeightInPoints((short)10); // 字體加粗 // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 設置字體名字 font.setFontName("Courier New"); // 設置樣式; HSSFCellStyle style = workbook.createCellStyle(); // 設置底邊框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 設置底邊框顏色; style.setBottomBorderColor(HSSFColor.BLACK.index); // 設置左邊框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 設置左邊框顏色; style.setLeftBorderColor(HSSFColor.BLACK.index); // 設置右邊框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); // 設置右邊框顏色; style.setRightBorderColor(HSSFColor.BLACK.index); // 設置頂邊框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); // 設置頂邊框顏色; style.setTopBorderColor(HSSFColor.BLACK.index); // 在樣式用應用設置的字體; style.setFont(font); // 設置自動換行; style.setWrapText(false); // 設置水平對齊的樣式為居中對齊; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 設置垂直對齊的樣式為居中對齊; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } /** * 關閉輸出流 * @param os */ private void close(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }
