日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java动态生成excel模板、和动态模板数据导出

發(fā)布時間:2023/12/10 java 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java动态生成excel模板、和动态模板数据导出 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1、添加依賴

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version> </dependency> <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version> </dependency> <dependency><groupId>com.monitorjbl</groupId><artifactId>xlsx-streamer</artifactId><version>2.1.0</version> </dependency>

2、導(dǎo)出excel工具類

package com.shucha.deveiface.biz.utils;import com.monitorjbl.xlsx.StreamingReader; import com.sdy.common.model.BizException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile;import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;@Slf4j public class ExcelUtil {/*** 數(shù)據(jù)導(dǎo)出成 Excel 數(shù)據(jù)格式** @param headList 表頭信息 (為null 或者 size() == 0 證明不存在)* @param dataList 數(shù)據(jù)信息* @return 結(jié)果數(shù)組*/public static byte[] exportExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsType) throws BizException {byte[] bytes = null;try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();ByteArrayOutputStream os = new ByteArrayOutputStream()) {int size = 65530; // int sheetCount = 0; // if (dataList.size() < size) { // // }int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));for (int i = 0; i < sheetCount; i++) {Sheet sheet = workbook.createSheet("sheet" + i);sheet.setDefaultColumnWidth(13);int rowIndex = 0;if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);rowIndex++;}int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);}workbook.write(os);bytes = os.toByteArray();} catch (Exception e) {throw new BizException("" + e);}return bytes;}// 寫入本地文件 防止內(nèi)存溢出public static void write(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {File file = new File(xlsxPath); // if (file.exists()) { // file.delete(); // }try (SXSSFWorkbook workbook = new SXSSFWorkbook();FileOutputStream outputStream = new FileOutputStream(file)) {int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));for (int i = 0; i < sheetCount; i++) {Sheet sheet = workbook.createSheet(i + "");sheet.setDefaultColumnWidth(13);int rowIndex = 0;if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);rowIndex++;}int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);}workbook.write(outputStream);} catch (Exception e) {log.error("", e);throw new BizException("" + e);}}//讀取本地文件 防止內(nèi)存溢出public static List<Map<String, Object>> readExcel(File file, Integer size, Integer current) throws BizException {try (InputStream is = new FileInputStream(file);Workbook workbook = StreamingReader.builder().rowCacheSize(100).bufferSize(4096).open(is)) {List<String> headerList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();for (Sheet sheet : workbook) {log.info(sheet.getSheetName());int start = (current * size) + 1;int end = start + 10;int i = 0;for (Row row : sheet) {if (i == 0) {for (Cell cell : row) {headerList.add(cell.getStringCellValue());}} else if (i > start && i <= end) {Map<String, Object> map = new HashMap<>();int j = 0;for (Cell cell : row) {map.put(headerList.get(j), cell.getStringCellValue());j++;}dataList.add(map);} else if (i > end) {break;}i++;}}return dataList;} catch (Exception e) {log.error("", e);throw new BizException("" + e);}}// public static void writeExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException { // File file = new File(xlsxPath); // if (file.exists()) { // file.delete(); // } // try (SXSSFWorkbook workbook = new SXSSFWorkbook(); // FileOutputStream outputStream = new FileOutputStream(file)) { // int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size)); // for (int i = 0; i < sheetCount; i++) { // Sheet sheet = workbook.createSheet(i + ""); // sheet.setDefaultColumnWidth(13); // int rowIndex = 0; // if (headList != null && headList.size() > 0) { // writerHeader(headList, sheet); // rowIndex++; // } // int end = dataList.size() > (size * (i + 1)) ? size : dataList.size(); // writerData(dataList.subList(i * size, end), headList, sheet, rowIndex); // } // workbook.write(outputStream); // } catch (Exception e) { // throw new BizException("" + e); // } // } // // public static void main(String[] args) throws BizException {List<String> headList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();headList.add("name");headList.add("value");for (int a = 0; a < 70000; a++) {Map<String, Object> map1 = new HashMap<>();map1.put("name", "測試name" + a);map1.put("value", "測試value" + a);dataList.add(map1);}write(headList, dataList, "/opt/1111.xlsx", 500000);List<Map<String, Object>> maps = readExcel(new File("D:/opt/1111.xlsx"), 10, 50);maps.size(); // Integer a = 0; // for (int i = 0; i < 10; i++) { // ExcelUtil excelUtil = new ExcelUtil(); // excelUtil.test(a); // System.out.println(a); // } // // } // // public void test(Integer a) { // a = a + 1; // }// public static void main(String[] args) throws Exception { // String rootPath = "D:/"; // createImage("檢察院看板", new Font("宋體", Font.PLAIN, 30), Paths.get(rootPath, "b" + 4000 + ".png").toFile()); // }// private static int[] getWidthAndHeight(String text, Font font) { // Rectangle2D r = font.getStringBounds(text, new FontRenderContext( // AffineTransform.getScaleInstance(1, 1), false, false)); // int unitHeight = (int) Math.floor(r.getHeight());// // // 獲取整個str用了font樣式的寬度這里用四舍五入后+1保證寬度絕對能容納這個字符串作為圖片的寬度 // int width = (int) Math.round(r.getWidth()) + 1; // // 把單個字符的高度+3保證高度絕對能容納字符串作為圖片的高度 // int height = unitHeight + 3; // System.out.println("width:" + width + ", height:" + height); // return new int[]{width, height};return new int[]{190, 28}; // } // // // 根據(jù)str,font的樣式以及輸出文件目錄 // public static void createImage(String text, Font font, File outFile) // throws Exception { // // 獲取font的樣式應(yīng)用在str上的整個矩形 // int[] arr = getWidthAndHeight(text, font); // int width = arr[0]; // int height = arr[1]; // // 創(chuàng)建圖片 // BufferedImage image = new BufferedImage(width, height, // BufferedImage.TYPE_INT_BGR);//創(chuàng)建圖片畫布 // Graphics g = image.getGraphics(); // g.setColor(Color.WHITE); // 先用白色填充整張圖片,也就是背景 // g.fillRect(0, 0, width, height);//畫出矩形區(qū)域,以便于在矩形區(qū)域內(nèi)寫入文字 // g.setColor(Color.black);// 再換成黑色,以便于寫入文字 // g.setFont(font);// 設(shè)置畫筆字體 // g.drawString(text, 0, font.getSize());// 畫出一行字符串 // g.drawString(text, 0, 2 * font.getSize());// 畫出第二行字符串,注意y軸坐標需要變動 // g.dispose(); // ImageIO.write(image, "png", outFile);// 輸出png圖片 // }public static byte[] exportExcelHead(List<String> headList, String xlsType) throws BizException {byte[] bytes = null;try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();ByteArrayOutputStream os = new ByteArrayOutputStream()) {Sheet sheet = workbook.createSheet(0 + "");sheet.setDefaultColumnWidth(13);if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);}workbook.write(os);bytes = os.toByteArray();} catch (Exception e) {throw new BizException("" + e);}return bytes;}/*** 寫表頭** @param headList 表頭List* @param sheet sheet*/public static void writerHeader(List<String> headList, Sheet sheet) {Row row = sheet.createRow(0);row.setHeightInPoints(21);RichTextString text;for (int i = 0; i < headList.size(); i++) {Cell cell = row.createCell((short) i);text = new XSSFRichTextString(headList.get(i));cell.setCellValue(text.toString());}}/*** 寫數(shù)據(jù)** @param dataList 數(shù)據(jù)* @param headList 表頭* @param sheet sheel* @param rowIndex 單元格索引*/public static void writerData(List<Map<String, Object>> dataList, List<String> headList, Sheet sheet, int rowIndex) {Row row;Cell cell;RichTextString text;for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowIndex + i);Map<String, Object> datas = dataList.get(i);for (int j = 0; j < headList.size(); j++) {cell = row.createCell(j);Object value = datas.get(headList.get(j));String data = value == null ? "" : String.valueOf(value);text = new XSSFRichTextString(data);cell.setCellValue(text);}}}public static Object getValue(Cell cell) {Object cellValue = "";if (cell != null) {//必須使用switch來獲取單元格數(shù)據(jù),否則會報錯,除非確保execl所有單元格的數(shù)據(jù)類型一致switch (cell.getCellType()) {case BOOLEAN://獲取布爾型數(shù)據(jù)cellValue = cell.getBooleanCellValue();break;case BLANK://獲取空值cellValue = cell.getBooleanCellValue();break;case ERROR://獲取錯誤單元格cellValue = cell.getErrorCellValue();break;case NUMERIC://獲取數(shù)字類型的數(shù)據(jù)cellValue = cell.getNumericCellValue();break;case STRING://獲取字符串cellValue = cell.getStringCellValue();break;}} else {cellValue = "";}return cellValue;}}

3、測試調(diào)用生成excel文件

@GetMapping("/template")@ApiOperation(value = "動態(tài)生成excel模板")public void templateDerive(HttpServletResponse response) throws BizException {List<String> paramList = new ArrayList<>();for (int i=0;i<5;i++) {paramList.add("標題名稱"+ i);}try {byte[] bytes = ExcelUtil.exportExcelHead(paramList, "xlsx");response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setCharacterEncoding("utf-8");String filename = "動態(tài)導(dǎo)出模板.xlsx";response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));response.getOutputStream().write(bytes);} catch (Exception e) {throw new BizException("模板文件生成失敗!原因:" + e);}}@GetMapping("/templateExcelData")@ApiOperation(value = "導(dǎo)出模板和數(shù)據(jù)")public void templateExcelData(HttpServletResponse response) throws BizException {List<String> headList = new ArrayList<>(); // for (int i=0;i<5;i++) { // headList.add("標題名稱"+ i); // } // List<String> headList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();headList.add("name");headList.add("value");for (int a = 0; a < 50; a++) {Map<String, Object> map1 = new HashMap<>();map1.put("name", "測試name" + a);map1.put("value", "測試value" + a);dataList.add(map1);} // List<Map<String, Object>> dataLis = new ArrayList<>(); // for (int j=0;j<5;j++){ // Map<String, Object> map = new HashMap<>(); // map.put("name","數(shù)據(jù)名稱"+j); // dataLis.add(map); // }try {byte[] bytes = ExcelUtil.exportExcel(headList, dataList, "xlsx");response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setCharacterEncoding("utf-8");String filename = "動態(tài)導(dǎo)出模板和數(shù)據(jù).xlsx";response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));response.getOutputStream().write(bytes);} catch (Exception e) {throw new BizException("模板文件生成失敗!原因:" + e);}}

總結(jié)

以上是生活随笔為你收集整理的Java动态生成excel模板、和动态模板数据导出的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。