Java实现Excel文件导出或者下载
生活随笔
收集整理的這篇文章主要介紹了
Java实现Excel文件导出或者下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以下是本人以前在實際項目中遇到的有關Excel文件通過瀏覽器下載或預覽的問題,謹以此記錄下來,以供后來參考。
1、maven依賴
<!-- 導出Excel --> <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.12</version> </dependency> <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.12</version> </dependency>2、Java實現通過瀏覽器下載
導出邏輯同下載邏輯相同,只需要在表格內插入導出數據。
(1)使用XSSFWorkbook創(chuàng)建表格
@ResponseBody @RequestMapping(value = "/downloadTemplate", method = RequestMethod.GET) public String downloadTemplate(HttpServletRequest request, HttpServletResponse response, String manufactureId) {String info = "";XSSFWorkbook xssfWorkbook = new XSSFWorkbook();// xls格式用HSSFWorkbook// HSSFSheettry {if (!CommonUtil.isNotEmpty(manufactureId)) {throw new Exception("param is null !");}//設置表頭格式XSSFCellStyle styleTitle = xssfWorkbook.createCellStyle();styleTitle.setBorderBottom(BorderStyle.THIN); //下邊框styleTitle.setBorderLeft(BorderStyle.THIN);//左邊框styleTitle.setBorderTop(BorderStyle.THIN);//上邊框styleTitle.setBorderRight(BorderStyle.THIN);//右邊框XSSFFont font = xssfWorkbook.createFont();font.setFontHeightInPoints((short) 12);// 字號font.setColor(HSSFColor.RED.index);styleTitle.setFont(font);styleTitle.setWrapText(true);//自動換行//設置單元格格式XSSFCellStyle textStyle = xssfWorkbook.createCellStyle();DataFormat format = xssfWorkbook.createDataFormat();textStyle.setDataFormat(format.getFormat("@"));// 設置單元格格式為"文本"textStyle.setBorderBottom(BorderStyle.THIN); //下邊框textStyle.setBorderLeft(BorderStyle.THIN);//左邊框textStyle.setBorderTop(BorderStyle.THIN);//上邊框textStyle.setBorderRight(BorderStyle.THIN);//右邊框textStyle.setVerticalAlignment(VerticalAlignment.CENTER);//居中//第一個頁簽XSSFSheet sheet1 = xssfWorkbook.createSheet();sheet1.setDefaultColumnWidth(20);// 設置默認列寬,width為字符個數//設置表格名稱xssfWorkbook.setSheetName(0, "離場申請模板");// 創(chuàng)建表格標題行 第一行XSSFRow titleRow = sheet1.createRow(0);String fileName = "離場申請模板.xlsx";String[] titles = {"編號\r\n(必填,從頁簽“已入場人員”中獲取)", "姓名\r\n(必填,從頁簽“已入場人員”中獲取)", "性別\r\n(必填,從頁簽“已入場人員”中獲取)", "離場時間\r\n(必填,格式:YYYY-MM-DD)", "是否離職\r\n(必填)","離職原因\r\n(當是否離職為“是”時,必填)"};for (int i = 0; i < titles.length; i++) {titleRow.createCell(i).setCellValue(titles[i]);titleRow.getCell(i).setCellStyle(styleTitle);sheet1.setDefaultColumnStyle(i, textStyle);}//第二個頁簽含人員記錄導出該廠商所有已入場狀態(tài)的人員XSSFSheet sheet2= xssfWorkbook.createSheet();sheet2.setDefaultColumnWidth(20);// 設置默認列寬,width為字符個數//設置表格名稱xssfWorkbook.setSheetName(1, "已入場人員");// 創(chuàng)建表格標題行 第一行XSSFRow titleRow2 = sheet2.createRow(0);String[] titles2 = {"編號", "姓名", "性別"};for (int i = 0; i < titles2.length; i++) {titleRow2.createCell(i).setCellValue(titles2[i]);titleRow2.getCell(i).setCellStyle(styleTitle);sheet2.setDefaultColumnStyle(i, textStyle);}//獲取該廠商下所有已入場的人員List<Map<String, Object>> listMap = this.leaveApplicationService.getManufactureStaffByManufactureId(Long.parseLong(manufactureId));for (int i = 0; i < listMap.size(); i++) {XSSFRow row = sheet2.createRow(i+1);Map<String, Object> order = listMap.get(i);row.createCell(0).setCellValue(order.get("ID")+"");row.getCell(0).setCellStyle(textStyle);row.createCell(1).setCellValue(order.get("NAME")+"");row.getCell(1).setCellStyle(textStyle);String sex = order.get("SEX") + "";if ("1".equals(sex)) {row.createCell(2).setCellValue("男");row.getCell(2).setCellStyle(textStyle);} else if ("2".equals(sex)) {row.createCell(2).setCellValue("女");row.getCell(2).setCellStyle(textStyle);}}// 瀏覽器下載response.reset();//重置瀏覽器,清空輸出流//不同瀏覽器的編碼設置String downloadFileName = URLEncoder.encode(fileName, "UTF-8");String agent = request.getHeader("User-Agent").toUpperCase();if (agent.indexOf("MSIE") > 0 || agent.indexOf("EDGE") > 0|| (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {response.setHeader("Content-disposition", "attachment; filename=" + downloadFileName);} else {response.setHeader("Content-disposition", "attachment; filename*=UTF-8''" + downloadFileName);}response.setCharacterEncoding("UTF-8");// response.setContentType("application/vnd.ms-excel;charset=GBK");xssfWorkbook.write(response.getOutputStream());info = "success";} catch (Exception e) {e.printStackTrace();log.error(e.getMessage(), e);request.setAttribute("error", "系統錯誤");info = "系統錯誤!";} finally {if (xssfWorkbook != null) {try {xssfWorkbook.close();xssfWorkbook = null;} catch (IOException e) {e.printStackTrace();}}// 添加用戶日志systemUtilService.addLog("WorkReportAction.downloadTemplate", info);}return info; } 下面是從瀏覽器上下載后的效果圖:sheet1:
sheet2:
(2)從服務器上下載
獲取配置文件:
/*** 獲取配置文件* @param path* @return Properties*/ public static Properties getProps(String path) {InputStream is = CmUtil.class.getResourceAsStream(path);Properties props = new Properties();try {props.load(is);} catch (IOException e) {e.printStackTrace();log.error(e.getMessage(),e);//throw new CommonException("加載配置文件錯誤");}finally{if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();log.error("不能關閉輸入文件",e);//throw new CommonException("關閉配置文件錯誤");}}}return props; }從服務器上獲取模板,然后通過瀏覽器下載:
@Override public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {OutputStream ops = null;FileInputStream fis = null;XSSFWorkbook xwb = null;try {String fileName = "離場申請模板.xlsx";//獲取模板在服務器上的地址String downloadPath = CmUtil.getProps("/conf.properties").getProperty("LEAVEFILE_TEMPLATE_PATH").trim();response.reset(); //重置瀏覽器,清空輸出流// 設置RESPONSEString downloadFileName = URLEncoder.encode(fileName, "UTF-8");String agent = request.getHeader("User-Agent").toUpperCase();if (agent.indexOf("MSIE") > 0 || agent.indexOf("EDGE") > 0|| (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);} else {response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + downloadFileName);}response.setCharacterEncoding("UTF-8");// response.setContentType("application/vnd.ms-excel;charset=GBK");String filePath = downloadPath + fileName;fis = new FileInputStream(filePath);xwb = new XSSFWorkbook(fis);fis.close();// 輸出流ops = response.getOutputStream();xwb.write(ops);} catch (Exception e) {e.printStackTrace();response.reset();try {OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";writer.write(data);writer.close();} catch (IOException e1) {e1.printStackTrace();}} finally {if (null != fis) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}if (null != xwb) {try {xwb.close();} catch (IOException e) {e.printStackTrace();}}if (null != ops) {try {ops.close();} catch (IOException e) {e.printStackTrace();}}} }POI-java讀取Excel(包含合并單元格):https://www.cnblogs.com/rain-in-summer/p/8243358.html
POI實現EXCEL單元格合并及邊框樣式:https://www.cnblogs.com/pejsidney/p/8383843.html
POI 分組合并單元格:https://www.iteye.com/blog/javasam-2082440
java代碼實現導出或者下載xml、word、pdf、excel功能:https://blog.csdn.net/until_tl/article/details/102912345
總結
以上是生活随笔為你收集整理的Java实现Excel文件导出或者下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Elasticsearch的Groovy
- 下一篇: 移植gdb到DM368 IPNC中 li