java自定義填充excel并導(dǎo)出的方法代碼實(shí)例
更新時(shí)間:2024年12月23日 09:14:30 作者:奔波霸的伶俐蟲
這篇文章主要給大家介紹了關(guān)于java自定義填充excel并導(dǎo)出的相關(guān)資料,使用Java在Spring框架中實(shí)現(xiàn)一個(gè)接口,該接口可以將JSON數(shù)據(jù)導(dǎo)出為Excel文件,文章涵蓋了從加載Excel模板、創(chuàng)建單元格樣式到填充數(shù)據(jù)并返回響應(yīng)的整個(gè)過程,需要的朋友可以參考下
首先在resources下面放一個(gè)excel模板
1. 方法簽名和請(qǐng)求映射
@RequestMapping(value = "/ExportXls") public ResponseEntity<byte[]> rwzcExportXls(HttpServletRequest request, @RequestBody JSONArray jsonArray) throws IOException {
@RequestMapping(value = "/rwzcExportXls")
:這個(gè)注解指定了HTTP請(qǐng)求的路徑,當(dāng)收到對(duì)/rwzcExportXls
的請(qǐng)求時(shí),調(diào)用rwzcExportXls
方法。ResponseEntity<byte[]>
:該方法返回一個(gè)包含字節(jié)數(shù)組的響應(yīng)實(shí)體,通常用于文件下載。HttpServletRequest
:用于獲取請(qǐng)求信息。@RequestBody JSONArray jsonArray
:請(qǐng)求體中的JSON數(shù)組,將被解析為JSONArray
對(duì)象。
2. 加載Excel模板
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates\\yhb.xlsx"); if (inputStream == null) { throw new IOException("Template file not found"); } Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0);
- 使用
ClassLoader
加載名為yhzcb.xlsx
的Excel模板文件。 - 如果文件未找到,則拋出
IOException
。 - 創(chuàng)建一個(gè)
Workbook
對(duì)象(使用XSSFWorkbook,表示Excel 2007及以上版本),并獲取第一個(gè)工作表。 - 也可以這樣加載模板
Resource resource = new ClassPathResource(TEMPLATE_FILE_PATH); try ( InputStream templateInputStream = resource.getInputStream(); Workbook workbook = new XSSFWorkbook(templateInputStream); OutputStream os = response.getOutputStream(); )
3. 創(chuàng)建單元格樣式
CellStyle centerAlignStyle = workbook.createCellStyle(); centerAlignStyle.setAlignment(HorizontalAlignment.CENTER); centerAlignStyle.setVerticalAlignment(VerticalAlignment.CENTER);
- 創(chuàng)建居中對(duì)齊的單元格樣式,設(shè)置水平和垂直對(duì)齊方式。
CellStyle borderStyle = workbook.createCellStyle(); borderStyle.cloneStyleFrom(centerAlignStyle); borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN);
- 創(chuàng)建一個(gè)邊框樣式,首先復(fù)制居中樣式,然后設(shè)置四個(gè)邊框?yàn)榧?xì)線。
4. 填充數(shù)據(jù)
int rowIndex = 4; for (int i = 0; i < jsonArray.size(); i++) { com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i); String shipDistrict = (String) jsonObject.get("shiprict"); // ... (獲取其他字段) Row row = sheet.createRow(rowIndex++); row.setHeightInPoints(34.9f); // 設(shè)置行高 createCellWithStyle(row, 1, "", borderStyle); // ... (創(chuàng)建并填充其他單元格) }
- 從第4行開始填充數(shù)據(jù)(假設(shè)前面有標(biāo)題行)。
- 循環(huán)遍歷
jsonArray
,從每個(gè)JSONObject
中提取字段,并在工作表中創(chuàng)建相應(yīng)的行和單元格。 - 使用輔助方法
createCellWithStyle
創(chuàng)建并設(shè)置單元格的值和樣式。
5. 寫入輸出流并返回響應(yīng)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close();
- 將工作簿寫入
ByteArrayOutputStream
,然后關(guān)閉工作簿。
HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=da.xlsx"); return ResponseEntity.ok() .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(outputStream.toByteArray());
- 設(shè)置響應(yīng)頭,指示這是一個(gè)附件,并指定文件名為
data.xlsx
。 - 返回
ResponseEntity
,內(nèi)容類型為application/octet-stream
,并包含生成的Excel文件的字節(jié)數(shù)組。 - 這可能會(huì)有異常提示
將 contentType里面改成下面即可
// 返回Excel文件 return ResponseEntity.ok() .headers(headers) .contentType(MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) .body(outputStream.toByteArray());
6. 輔助方法
// 輔助方法:創(chuàng)建單元格并應(yīng)用樣式 private void createCellWithStyle(Row row, int columnIndex, String value, CellStyle style) { Cell cell = row.createCell(columnIndex); cell.setCellValue(value); cell.setCellStyle(style); }
- 該方法簡(jiǎn)化了單元格的創(chuàng)建過程,自動(dòng)設(shè)置單元格的值和樣式。
完整代碼如下
@RequestMapping(value = "/ExportXls") public ResponseEntity<byte[]> rwzcExportXls(HttpServletRequest request,@RequestBody JSONArray jsonArray) throws IOException { // 讀取模板 // 使用ClassLoader加載模板 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/excel/yb.xlsx"); if (inputStream == null) { throw new IOException("Template file not found" ); } Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // 假設(shè)數(shù)據(jù)填充在第一個(gè)Sheet // 創(chuàng)建居中對(duì)齊的單元格樣式 CellStyle centerAlignStyle = workbook.createCellStyle(); centerAlignStyle.setAlignment(HorizontalAlignment.CENTER); centerAlignStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 創(chuàng)建邊框樣式 CellStyle borderStyle = workbook.createCellStyle(); borderStyle.cloneStyleFrom(centerAlignStyle); // 復(fù)制之前的居中樣式 borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN); // 從第4行開始填充數(shù)據(jù)(第一行是標(biāo)題) int rowIndex = 4; for (int i = 0; i < jsonArray.size(); i++) { com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i); String shipDistrict = (String) jsonObject.get("shipDistrict"); shipDistrict = shipDistrict.substring(0, 2)+"0000"; SysDistrict district = sysDistrictService.getById(shipDistrict); String owname = (String) jsonObject.get("owneame"); *********************** String shio = (String) jsonObject.get("shiNo"); Row row = sheet.createRow(rowIndex++); row.setHeightInPoints(34.9f); // 設(shè)置行高為34.9磅 createCellWithStyle(row, 1, "", borderStyle); createCellWithStyle(row, 2, "通信類", borderStyle); ******************************** createCellWithStyle(row, 15, "", borderStyle); createCellWithStyle(row, 16, "", borderStyle); createCellWithStyle(row, 17, "", borderStyle); createCellWithStyle(row, 18, shiame, borderStyle); createCellWithStyle(row, 19, shNo, borderStyle); // 根據(jù)需要繼續(xù)填充其他字段 } // 寫入到新的Excel文件 //FileOutputStream fos = new FileOutputStream("D:\\opt"); //workbook.write(fos); 關(guān)閉流 //fos.close(); //workbook.close(); // // 將工作簿寫入輸出流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close(); // 設(shè)置響應(yīng)頭 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=da.xlsx"); // 返回Excel文件 return ResponseEntity.ok() .headers(headers) .contentType(MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) .body(outputStream.toByteArray()); } // 輔助方法:創(chuàng)建單元格并應(yīng)用樣式 private void createCellWithStyle(Row row, int columnIndex, String value, CellStyle style) { Cell cell = row.createCell(columnIndex); cell.setCellValue(value); cell.setCellStyle(style); }
總結(jié)
到此這篇關(guān)于java自定義填充excel并導(dǎo)出的文章就介紹到這了,更多相關(guān)java自定義填充excel并導(dǎo)出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis-Plus中update()和updateById()將字段更新為null
本文主要介紹了Mybatis-Plus中update()和updateById()將字段更新為null,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08java中Supplier知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于java中Supplier知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-04-04Quartz定時(shí)任務(wù)管理方式(動(dòng)態(tài)添加、停止、恢復(fù)、刪除定時(shí)任務(wù))
這篇文章主要介紹了Quartz定時(shí)任務(wù)管理方式(動(dòng)態(tài)添加、停止、恢復(fù)、刪除定時(shí)任務(wù)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12