基於Spring3 MVC實現批量匯出資料成Excel檔案!
阿新 • • 發佈:2019-01-30
在jsp中:
<button onclick="download()" class="btn btn-warning " type="button">批量匯出Excel <i class="fa fa-download"></i></button>
MasterChildController.java:<script type="text/javascript"> //匯出資訊函式 function download(){ if(confirm("是否要匯出資料?")){ var url = "${path}/master/child/downloadChild"; $.post(url,function(data){ alert(data.message); }); } } </script>
ExcelUtil.java 對Excel操作的工具類。@RequestMapping(value = "downloadChild", method = RequestMethod.POST) @ResponseBody public Map<String, Object> downloadChild() throws Exception { Date date = new Date(); DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String fileName = sdf.format(date); //得到桌面路徑 File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory(); String desktopPath = desktopDir.getAbsolutePath(); String desktopDirPath = desktopPath.replace("\\","\\\\"); String filePath = desktopDirPath + "\\\\" +fileName + ".xls"; //System.out.println(filePath); String[] titles = {"年級班級名稱","幼兒學號","姓名","性別","年齡","出生日期","新增幼兒時間","刪除標誌","父親姓名","父親電話","父親工作單位","母親姓名","母親電話","母親工作單位","家庭住址","備註"}; Map<String, Object> params = new HashMap<String, Object>(); List<Child> listsChild = childService.queryAll(params); Grades grades = new Grades(); SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<Map<Integer, String>> lists = new ArrayList<Map<Integer,String>>(); for (int i = 0; i < listsChild.size(); i++) { Child child = listsChild.get(i); Map<Integer, String> paramsLists = new HashMap<Integer, String>(); //通過child.getGradesId()來查詢班級名稱 grades = gradesService.queryBean(child.getGradesId()); paramsLists.put(0, grades.getGradesName()); paramsLists.put(1, child.getChildNo()); paramsLists.put(2, child.getChildName()); paramsLists.put(3, child.getSex()); paramsLists.put(4, child.getAge().toString()); paramsLists.put(5, child.getBrithDay()); //格式化新增幼兒時間 paramsLists.put(6, dateFormater.format(child.getAddDate())); paramsLists.put(7, child.getDr()); paramsLists.put(8, child.getFatherName()); paramsLists.put(9, child.getFatherPhone()); paramsLists.put(10, child.getFatherWork()); paramsLists.put(11, child.getMotherName()); paramsLists.put(12, child.getMotherPhone()); paramsLists.put(13, child.getMotherWork()); paramsLists.put(14, child.getAddress()); paramsLists.put(15, child.getComments()); lists.add(paramsLists); } ExcelUtil.writeExcel(filePath, titles, lists); Map<String,Object> json = new HashMap<String, Object>(); json.put("message", "匯出Excel檔案到桌面,檔名為:" + fileName + ".xls"); return json; }
public class ExcelUtil { /** * @info 寫出Excel標題 * @param fos * @return */ public static void writeExcelTitle(String filePath, String[] ss) throws IOException { OutputStream fos = new FileOutputStream(filePath); HSSFWorkbook xls = new HSSFWorkbook(); HSSFSheet sheet = xls.createSheet(); HSSFRow row = sheet.createRow(0);// 第一行 for (int i = 0; i < ss.length; i++) { row.createCell(i).setCellValue(ss[i]); } xls.write(fos); fos.close(); } /** * @info 寫出Excel標題內容 * @param fos * @return */ public static byte[] writeExcel(String[] titles, List<Map<Integer, String>> lists) throws IOException { HSSFWorkbook xls = new HSSFWorkbook(); HSSFSheet sheet = xls.createSheet(); HSSFRow row = sheet.createRow(0);// 第一行 for (int i = 0; i < titles.length; i++) { row.createCell(i).setCellValue(titles[i]); } // 內容 int rowNum = 1; for (Map<Integer, String> map : lists) { HSSFRow rowTmp = sheet.createRow(rowNum); int cols = map.size(); for (int i = 0; i < cols; i++) { rowTmp.createCell(i).setCellValue(map.get(i)); } rowNum++; } ByteArrayOutputStream fos = new ByteArrayOutputStream(); xls.write(fos); byte[] buf = fos.toByteArray();// 獲取記憶體緩衝區中的資料 fos.close(); return buf; } /** * @info 寫出Excel標題內容 * @param fos * @return */ public static void writeExcel(String filePath, String[] titles, List<Map<Integer, String>> lists) throws IOException { OutputStream fos = new FileOutputStream(filePath); HSSFWorkbook xls = new HSSFWorkbook(); HSSFSheet sheet = xls.createSheet(); HSSFRow row = sheet.createRow(0);// 第一行 for (int i = 0; i < titles.length; i++) { row.createCell(i).setCellValue(titles[i]); } // 內容 int rowNum = 1; for (Map<Integer, String> map : lists) { HSSFRow rowTmp = sheet.createRow(rowNum); int cols = map.size(); for (int i = 0; i < cols; i++) { rowTmp.createCell(i).setCellValue(map.get(i)); } rowNum++; } xls.write(fos); fos.close(); } /** * @info 讀取Excel內容,List行,MAP行資料 * @param filePath * @return */ public static List<Map<String, String>> readExcelKeyMap(String filePath) throws IOException { List<Map<String, String>> contents = new LinkedList<Map<String, String>>(); InputStream is = new FileInputStream(filePath); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); HSSFRow row = sheet.getRow(0);// 第一行 // 總列數 int colNum = row.getPhysicalNumberOfCells(); // 正文內容應該從第二行開始,第一行為表頭的標題 String[] keys = readExcelTitle(filePath); for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; Map<String, String> content = new HashMap<String, String>(); while (j < colNum) { String cellValue = getCellFormatValue(row.getCell(j)).trim(); content.put(keys[j], cellValue); j++; } contents.add(content); } is.close(); return contents; } public static List<Map<String, String>> readExcelKeyMap(InputStream is) throws IOException { List<Map<String, String>> contents = new LinkedList<Map<String, String>>(); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); HSSFRow row = sheet.getRow(0);// 第一行 // 總列數 int colNum = row.getPhysicalNumberOfCells(); // 正文內容應該從第二行開始,第一行為表頭的標題 // 標題總列數 String[] keys = new String[colNum]; for (int i = 0; i < colNum; i++) { keys[i] = getCellFormatValue(row.getCell(i)); } for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; Map<String, String> content = new HashMap<String, String>(); while (j < colNum) { String cellValue = getCellFormatValue(row.getCell(j)).trim(); content.put(keys[j], cellValue); j++; } contents.add(content); } is.close(); return contents; } /** * @info 讀取Excel標題 * @param is * @return */ public static String[] readExcelTitle(String filePath) throws IOException { InputStream is = new FileInputStream(filePath); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(0);// 第一行 // 標題總列數 int colNum = row.getPhysicalNumberOfCells(); String[] title = new String[colNum]; for (int i = 0; i < colNum; i++) { title[i] = getCellFormatValue(row.getCell(i)); } is.close(); return title; } /** * @info 讀取Excel內容,List行,MAP行資料 * @param filePath * @return */ public static List<Map<Integer, String>> readExcelContent(String filePath) throws IOException { List<Map<Integer, String>> contents = new LinkedList<Map<Integer, String>>(); InputStream is = new FileInputStream(filePath); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); HSSFRow row = sheet.getRow(0);// 第一行 // 總列數 int colNum = row.getPhysicalNumberOfCells(); // 正文內容應該從第二行開始,第一行為表頭的標題 for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; Map<Integer, String> content = new HashMap<Integer, String>(); while (j < colNum) { String cellValue = getCellFormatValue(row.getCell(j)).trim(); content.put(j, cellValue); j++; } contents.add(content); } is.close(); return contents; } /** * @info 讀取Excel值 * @param cell * @return */ static String getCellFormatValue(HSSFCell cell) { String cellvalue = ""; if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: { BigDecimal b = new BigDecimal(cell.getNumericCellValue()); cellvalue = b.toPlainString(); break; } case HSSFCell.CELL_TYPE_FORMULA: { cell.setCellType(Cell.CELL_TYPE_STRING); cellvalue = cell.getStringCellValue(); //System.out.println(cellvalue); break; } case HSSFCell.CELL_TYPE_STRING: cellvalue = cell.getRichStringCellValue().getString(); //System.out.println(cellvalue); break; default: cellvalue = ""; } } else { cellvalue = ""; } return cellvalue; } /** * @info 讀取Excel值 * @param cell * @return */ static String getStringCellValue(HSSFCell cell) { String strCell = ""; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: strCell = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: strCell = String.valueOf(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: strCell = ""; break; default: strCell = ""; break; } if (strCell.equals("") || strCell == null) { return ""; } return strCell; } }