java自定義填充excel并導(dǎo)出的方法代碼實(shí)例
首先在resources下面放一個(gè)excel模板
1. 方法簽名和請求映射
@RequestMapping(value = "/ExportXls") public ResponseEntity<byte[]> rwzcExportXls(HttpServletRequest request, @RequestBody JSONArray jsonArray) throws IOException {@RequestMapping(value = "/rwzcExportXls"):這個(gè)注解指定了HTTP請求的路徑,當(dāng)收到對/rwzcExportXls的請求時(shí),調(diào)用rwzcExportXls方法。ResponseEntity<byte[]>:該方法返回一個(gè)包含字節(jié)數(shù)組的響應(yīng)實(shí)體,通常用于文件下載。HttpServletRequest:用于獲取請求信息。@RequestBody JSONArray jsonArray:請求體中的JSON數(shù)組,將被解析為JSONArray對象。
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對象(使用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)建居中對齊的單元格樣式,設(shè)置水平和垂直對齊方式。
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ù)組。 - 這可能會有異常提示

將 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);
}- 該方法簡化了單元格的創(chuà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)建居中對齊的單元格樣式
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
HandlerMapping之RequestMappingHandlerMapping作用詳解
這篇文章主要介紹了HandlerMapping之RequestMappingHandlerMapping作用詳解,HandlerMapping是用來尋找Handler的,并不與Handler的類型或者實(shí)現(xiàn)綁定,而是根據(jù)需要定義的,那么為什么要單獨(dú)給@RequestMapping實(shí)現(xiàn)一個(gè)HandlerMapping,需要的朋友可以參考下2023-10-10
Java優(yōu)化重復(fù)冗余代碼的8種方式總結(jié)
日常開發(fā)中,我們經(jīng)常會遇到一些重復(fù)代碼,最近小編優(yōu)化了一些系統(tǒng)中的重復(fù)代碼,用了好幾種的方式,感覺挺有用的,所以本文給大家講講優(yōu)化重復(fù)代碼的幾種方式2023-08-08
Spring Cloud Gateway層限流實(shí)現(xiàn)過程
這篇文章主要介紹了Spring Cloud Gateway層限流實(shí)現(xiàn)過程,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
SpringBoot中@EnableAsync和@Async注解的使用小結(jié)
在SpringBoot中,可以通過@EnableAsync注解來啟動異步方法調(diào)用的支持,通過@Async注解來標(biāo)識異步方法,讓方法能夠在異步線程中執(zhí)行,本文就來介紹一下,感興趣的可以了解一下2023-11-11
SpringBoot項(xiàng)目啟動后再請求遠(yuǎn)程接口的解決方式
Spring?Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡化Spring應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等,這篇文章主要介紹了SpringBoot項(xiàng)目啟動后再請求遠(yuǎn)程接口的實(shí)現(xiàn)方式?,需要的朋友可以參考下2023-02-02

