1. 程式人生 > >SpringMVC 匯入匯出Excel檔案

SpringMVC 匯入匯出Excel檔案

/**
  * 下載Excel模板 建立一個新的檔案用於下載,建立的檔案放在快取中
  *
  * @param request
  * @param response
  */
 /*
  * @RequestMapping("/get_Sb_yys_sgyyqk_cj") public void
  * get_Sb_yys_sgyyqk_cj(HttpServletRequest request, HttpServletResponse
  * response) { try { // 輸出流 OutputStream os = new
  * FileOutputStream(filePath); // 工作區 HSSFWorkbook wb = new HSSFWorkbook();
  * // 工作區名 HSSFSheet sheet = wb.createSheet("菸葉稅採集模板");
  * sheet.autoSizeColumn(1, true); // 設定自適應寬度,高版本的POI才有用
  *
  * // 建立表頭 HSSFRow row = sheet.createRow(0); row.setHeight((short) 600);//
  * 設定行的高度
  *
  * // 設定單元格內容格式 HSSFCellStyle style = wb.createCellStyle();
  * style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平佈局:居中
  * style.setWrapText(true);// 自動換行
  *
  * // 設定單元格內容格式 HSSFCellStyle style1 = wb.createCellStyle(); //
  * 測試發現excel不支援精確到秒的日期格式,換成日期就夠 //
  * style1.setDataFormat(HSSFDataFormat.getBuiltinFormat
  * ("yyyy/MM/dd hh:mm:ss"));
  * style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy-MM-dd"));
  * style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平佈局:居中
  * style1.setWrapText(true);// 自動換行
  *
  * HSSFCell cell = row.createCell(0); cell.setCellStyle(style);
  * cell.setCellValue("社會信用程式碼"); sheet.autoSizeColumn((short) 1); //
  * sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); // //
  * 合併單元格(startRow,endRow,startColumn,endColumn)
  *
  * cell = row.createCell(1); cell.setCellStyle(style);
  * cell.setCellValue("收購數量");
  *
  * cell = row.createCell(2); cell.setCellStyle(style);
  * cell.setCellValue("單價");
  *
  * cell = row.createCell(3); cell.setCellStyle(style);
  * cell.setCellValue("菸葉等級程式碼"); sheet.autoSizeColumn((short) 3); // 調整第3列寬度
  *
  * cell = row.createCell(4); cell.setCellStyle(style1);
  * cell.setCellValue("收購日期(資料格式為yyyy-MM-dd,如:2017-12-11表示2017年12月11日)");
  * sheet.autoSizeColumn((short) 4); // 調整第四列寬度
  *
  * // 寫檔案 wb.write(os); // 關閉輸出流 os.close(); download(filePath, response); }
  * catch (Exception e) { e.printStackTrace(); } }
  *//**
  * 此方法可以提出去公用
  *
  * @param path
  * @param response
  */
 /*
  * private void download(String path, HttpServletResponse response) { try {
  * // path是指欲下載的檔案的路徑。 File file = new File(path); // 取得檔名。 String filename
  * = file.getName(); // 以流的形式下載檔案。 InputStream fis = new
  * BufferedInputStream(new FileInputStream(path)); byte[] buffer = new
  * byte[fis.available()]; fis.close(); // 清空response response.reset(); //
  * 設定response的Header response.addHeader("Content-Disposition",
  * "attachment;filename=" + new String(filename.getBytes()));
  * response.addHeader("Content-Length", "" + file.length()); OutputStream
  * toClient = new BufferedOutputStream( response.getOutputStream());
  * response.setContentType("application/vnd.ms-excel;charset=utf-8");
  * toClient.write(buffer); toClient.flush(); toClient.close();
  * if(file.exists()){ //刪除快取的檔案 file.delete(); } } catch (IOException ex) {
  * ex.printStackTrace(); } }
  */