WEB下载数据量大的EXCEL解决方案
生活随笔
收集整理的這篇文章主要介紹了
WEB下载数据量大的EXCEL解决方案
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
思路:需要2次請(qǐng)求,第一次ajax請(qǐng)求把數(shù)據(jù)查詢出來,按照1000條數(shù)據(jù)一個(gè)sheet,在后臺(tái)生成臨時(shí)文件,并把文件名稱返回給web,第二次請(qǐng)求直接下載臨時(shí)文件下載完成后,刪除臨時(shí)文件
代碼如下web端:
// 導(dǎo)出 function cmd_toExcel() {$.messager.progress({ title: '請(qǐng)等待', msg: "<span style='color:green'>人生若只如初見</span>", text: '努力下載中.......' });$.ajax({type : "post",url : cmd.toexport,data : formToObject('.searchBox'),dataType : "json",success : function(data) {location.href = _ctx + "/rest/download/getfile?name=" + data + "&originFileName=" + "車輛統(tǒng)計(jì).xls";$.messager.progress('close');}}); }?后臺(tái)服務(wù)端,生成臨時(shí)文件接口:
/*** 導(dǎo)出* * @throws Exception*/@RequestMapping(value = "/toexport", method = { RequestMethod.POST, RequestMethod.GET })@ResponseBodypublic String export(HttpServletRequest request, String area, Integer trans, String org, String no,AnalysisDate analysisdate, @RequestParam(required = false, defaultValue = "VEH_ID") String sort,@RequestParam(required = false, defaultValue = "asc") String order) throws Exception {Pageable pageable = new PageRequest(0, 1000000, new Sort("asc".equalsIgnoreCase(order) ? Direction.ASC: Direction.DESC, sort, "VEH_ID"));List<Map<String, Object>> list = manager.statistics(area, trans, org, no, analysisdate,SpringSecurityUtils.getCurrentUserArea(), pageable).getContent();String title = "車輛統(tǒng)計(jì)表";String[] rowsName = new String[] {"序號(hào)", "道路運(yùn)輸證號(hào)", "車牌", "企業(yè)名稱", "所屬區(qū)域", "運(yùn)輸行業(yè)分類", "車輛類型", "上線時(shí)長(zhǎng)", "斷開時(shí)長(zhǎng)", "報(bào)警次數(shù)"};List<Object[]> dataList = new ArrayList<Object[]>();Object[] objs = null;for (int i = 0; i < list.size(); i++) {Map<String, Object> man = list.get(i);objs = new Object[rowsName.length];objs[0] = i;objs[1] = man.get("RTPN");objs[2] = man.get("VEH_ID") == null ? "" : man.get("VEH_ID");objs[3] = man.get("ORG_NAME") == null ? "" : man.get("ORG_NAME");objs[4] = man.get("AREANAME");objs[5] = man.get("TRANS_TYPE");objs[6] = man.get("VTYPE");objs[7] = durationFormatter(((BigDecimal)man.get("ONLINE_TIME")).intValue());objs[8] = durationFormatter(((BigDecimal)man.get("OFF_TIME")).intValue());objs[9] = man.get("WARN_AMOUNT");dataList.add(objs);}ExportExcel ex = new ExportExcel(title, rowsName, dataList, request);return ex.export();} package com.wttech.gnss.utils;import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID;import javax.servlet.http.HttpServletRequest;import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.hssf.util.HSSFColor;/*** 導(dǎo)出Excel公共方法* **/ public class ExportExcel {// 顯示的導(dǎo)出表的標(biāo)題private String title;// 導(dǎo)出表的列名private String[] rowName;private List<Object[]> dataList = new ArrayList<Object[]>();HttpServletRequest request;// 構(gòu)造方法,傳入要導(dǎo)出的數(shù)據(jù)public ExportExcel(String title, String[] rowName, List<Object[]> dataList, HttpServletRequest request) {this.request = request;this.dataList = dataList;this.rowName = rowName;this.title = title;}/** 導(dǎo)出數(shù)據(jù)*/@SuppressWarnings("deprecation")public String export() throws Exception {String uuid = "/temp_" + UUID.randomUUID().toString() + ".xls";String filename = Properties.UPLOAD_ADDRESS + uuid;try {HSSFWorkbook workbook = new HSSFWorkbook(); // 創(chuàng)建工作簿對(duì)象int sheets = dataList.size() / 50000 + 1;for (int m = 0; m < sheets; m++) {HSSFSheet sheet = workbook.createSheet(title + m); // 創(chuàng)建工作表// 產(chǎn)生表格標(biāo)題行HSSFRow rowm = sheet.createRow(0);HSSFCell cellTiltle = rowm.createCell(0);// sheet樣式定義【getColumnTopStyle()/getStyle()均為自定義方法 - 在下面 - 可擴(kuò)展】HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 獲取列頭樣式對(duì)象HSSFCellStyle style = this.getStyle(workbook); // 單元格樣式對(duì)象HSSFCellStyle headerStyle = getHeaderStyle(workbook);sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));cellTiltle.setCellStyle(headerStyle);cellTiltle.setCellValue(title);// 定義所需列數(shù)int columnNum = rowName.length;HSSFRow rowRowName = sheet.createRow(2); // 在索引3的位置創(chuàng)建行(最頂端的行開始的第3行)// 將列頭設(shè)置到sheet的單元格中for (int n = 0; n < columnNum; n++) {HSSFCell cellRowName = rowRowName.createCell(n); // 創(chuàng)建列頭對(duì)應(yīng)個(gè)數(shù)的單元格cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 設(shè)置列頭單元格的數(shù)據(jù)類型HSSFRichTextString text = new HSSFRichTextString(rowName[n]);cellRowName.setCellValue(text); // 設(shè)置列頭單元格的值cellRowName.setCellStyle(columnTopStyle); // 設(shè)置列頭單元格樣式}// 將查詢出的數(shù)據(jù)設(shè)置到sheet對(duì)應(yīng)的單元格中List<Object[]> sub = dataList.subList(m * 50000, (m + 1) * 50000 < dataList.size() ? (m + 1) * 50000: dataList.size());for (int i = 0; i < sub.size(); i++) {Object[] obj = sub.get(i);// 遍歷每個(gè)對(duì)象HSSFRow row = sheet.createRow(i + 3);// 創(chuàng)建所需的行數(shù)for (int j = 0; j < obj.length; j++) {HSSFCell cell = null; // 設(shè)置單元格的數(shù)據(jù)類型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 (obj[j] != null) {cell.setCellValue(obj[j].toString()); // 設(shè)置單元格的值} else {cell.setCellValue(""); // 設(shè)置單元格的值}}cell.setCellStyle(style); // 設(shè)置單元格樣式}}// 讓列寬隨著導(dǎo)出的列長(zhǎng)自動(dòng)適應(yīng)for (int colNum = 0; colNum < columnNum; colNum++) {switch (colNum) {case 0:sheet.setColumnWidth(colNum, 6 * 256);break;default:sheet.setColumnWidth(colNum, 20 * 256);break;}}}if (workbook != null) {try {File file = new File(filename);// 以流的形式下載文件。BufferedOutputStream fis = new BufferedOutputStream(new FileOutputStream(file));workbook.write(fis);fis.flush();// 刷新流fis.close();// 關(guān)閉流} catch (IOException e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}return uuid;}/** 表頭單元格樣式*/public HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {// 設(shè)置字體HSSFFont font = workbook.createFont();// 設(shè)置字體大小font.setFontHeightInPoints((short) 11);// 字體加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設(shè)置字體名字font.setFontName("Courier New");// 設(shè)置樣式;HSSFCellStyle style = workbook.createCellStyle();// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動(dòng)換行;style.setWrapText(false);// 設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/** 表頭單元格樣式*/public HSSFCellStyle getRightStyle(HSSFWorkbook workbook) {// 設(shè)置字體HSSFFont font = workbook.createFont();// 設(shè)置字體大小font.setFontHeightInPoints((short) 11);// 字體加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設(shè)置字體名字font.setFontName("Courier New");// 設(shè)置樣式;HSSFCellStyle style = workbook.createCellStyle();// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動(dòng)換行;style.setWrapText(false);// 設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/** 列頭單元格樣式*/public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {// 設(shè)置字體HSSFFont font = workbook.createFont();// 設(shè)置字體大小font.setFontHeightInPoints((short) 11);// 字體加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設(shè)置字體名字font.setFontName("Courier New");// 設(shè)置樣式;HSSFCellStyle style = workbook.createCellStyle();// 設(shè)置底邊框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 設(shè)置底邊框顏色;style.setBottomBorderColor(HSSFColor.BLACK.index);// 設(shè)置左邊框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 設(shè)置左邊框顏色;style.setLeftBorderColor(HSSFColor.BLACK.index);// 設(shè)置右邊框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 設(shè)置右邊框顏色;style.setRightBorderColor(HSSFColor.BLACK.index);// 設(shè)置頂邊框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 設(shè)置頂邊框顏色;style.setTopBorderColor(HSSFColor.BLACK.index);// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動(dòng)換行;style.setWrapText(false);// 設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/** 表頭單元格樣式*/public HSSFCellStyle getFootStyle(HSSFWorkbook workbook) {// 設(shè)置字體HSSFFont font = workbook.createFont();// 設(shè)置字體大小font.setFontHeightInPoints((short) 11);// 字體加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設(shè)置字體名字font.setFontName("Courier New");// 設(shè)置樣式;HSSFCellStyle style = workbook.createCellStyle();// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動(dòng)換行;style.setWrapText(false);// 設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/** 列數(shù)據(jù)信息單元格樣式*/public HSSFCellStyle getStyle(HSSFWorkbook workbook) {// 設(shè)置字體HSSFFont font = workbook.createFont();// 設(shè)置字體大小// font.setFontHeightInPoints((short)10);// 字體加粗// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設(shè)置字體名字font.setFontName("Courier New");// 設(shè)置樣式;HSSFCellStyle style = workbook.createCellStyle();// 設(shè)置底邊框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 設(shè)置底邊框顏色;style.setBottomBorderColor(HSSFColor.BLACK.index);// 設(shè)置左邊框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 設(shè)置左邊框顏色;style.setLeftBorderColor(HSSFColor.BLACK.index);// 設(shè)置右邊框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 設(shè)置右邊框顏色;style.setRightBorderColor(HSSFColor.BLACK.index);// 設(shè)置頂邊框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 設(shè)置頂邊框顏色;style.setTopBorderColor(HSSFColor.BLACK.index);// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動(dòng)換行;style.setWrapText(false);// 設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置垂直對(duì)齊的樣式為居中對(duì)齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;} }接口2下載臨時(shí)文件,并刪除
@RequestMapping(value = "/getfile")@ResponseBodypublic void getfile(HttpServletRequest request,HttpServletResponse response,String name,String originFileName) throws ParseException {String path = Properties.UPLOAD_ADDRESS + name ;File file = new File(path);// 以流的形式下載文件。InputStream fis;try {fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();response.reset();response.addHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(originFileName, "UTF-8"));response.setCharacterEncoding("utf-8");response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();toClient.close();if (name.contains("temp")) {file.delete();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}?
轉(zhuǎn)載于:https://my.oschina.net/chuibilong/blog/845053
總結(jié)
以上是生活随笔為你收集整理的WEB下载数据量大的EXCEL解决方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿里巴巴2018秋招总结
- 下一篇: QT的OpenGL进行模型的3D展示