java自定义填充excel并导出的方法代码实例
作者:奔波霸的伶俐虫
这篇文章主要给大家介绍了关于java自定义填充excel并导出的相关资料,使用Java在Spring框架中实现一个接口,该接口可以将JSON数据导出为Excel文件,文章涵盖了从加载Excel模板、创建单元格样式到填充数据并返回响应的整个过程,需要的朋友可以参考下
首先在resources下面放一个excel模板
1. 方法签名和请求映射
@RequestMapping(value = "/ExportXls") public ResponseEntity<byte[]> rwzcExportXls(HttpServletRequest request, @RequestBody JSONArray jsonArray) throws IOException {
@RequestMapping(value = "/rwzcExportXls")
:这个注解指定了HTTP请求的路径,当收到对/rwzcExportXls
的请求时,调用rwzcExportXls
方法。ResponseEntity<byte[]>
:该方法返回一个包含字节数组的响应实体,通常用于文件下载。HttpServletRequest
:用于获取请求信息。@RequestBody JSONArray jsonArray
:请求体中的JSON数组,将被解析为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
。 - 创建一个
Workbook
对象(使用XSSFWorkbook,表示Excel 2007及以上版本),并获取第一个工作表。 - 也可以这样加载模板
Resource resource = new ClassPathResource(TEMPLATE_FILE_PATH); try ( InputStream templateInputStream = resource.getInputStream(); Workbook workbook = new XSSFWorkbook(templateInputStream); OutputStream os = response.getOutputStream(); )
3. 创建单元格样式
CellStyle centerAlignStyle = workbook.createCellStyle(); centerAlignStyle.setAlignment(HorizontalAlignment.CENTER); centerAlignStyle.setVerticalAlignment(VerticalAlignment.CENTER);
- 创建居中对齐的单元格样式,设置水平和垂直对齐方式。
CellStyle borderStyle = workbook.createCellStyle(); borderStyle.cloneStyleFrom(centerAlignStyle); borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN);
- 创建一个边框样式,首先复制居中样式,然后设置四个边框为细线。
4. 填充数据
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); // 设置行高 createCellWithStyle(row, 1, "", borderStyle); // ... (创建并填充其他单元格) }
- 从第4行开始填充数据(假设前面有标题行)。
- 循环遍历
jsonArray
,从每个JSONObject
中提取字段,并在工作表中创建相应的行和单元格。 - 使用辅助方法
createCellWithStyle
创建并设置单元格的值和样式。
5. 写入输出流并返回响应
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close();
- 将工作簿写入
ByteArrayOutputStream
,然后关闭工作簿。
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());
- 设置响应头,指示这是一个附件,并指定文件名为
data.xlsx
。 - 返回
ResponseEntity
,内容类型为application/octet-stream
,并包含生成的Excel文件的字节数组。 - 这可能会有异常提示
将 contentType里面改成下面即可
// 返回Excel文件 return ResponseEntity.ok() .headers(headers) .contentType(MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) .body(outputStream.toByteArray());
6. 辅助方法
// 辅助方法:创建单元格并应用样式 private void createCellWithStyle(Row row, int columnIndex, String value, CellStyle style) { Cell cell = row.createCell(columnIndex); cell.setCellValue(value); cell.setCellStyle(style); }
- 该方法简化了单元格的创建过程,自动设置单元格的值和样式。
完整代码如下
@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); // 假设数据填充在第一个Sheet // 创建居中对齐的单元格样式 CellStyle centerAlignStyle = workbook.createCellStyle(); centerAlignStyle.setAlignment(HorizontalAlignment.CENTER); centerAlignStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 创建边框样式 CellStyle borderStyle = workbook.createCellStyle(); borderStyle.cloneStyleFrom(centerAlignStyle); // 复制之前的居中样式 borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN); // 从第4行开始填充数据(第一行是标题) 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); // 设置行高为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); // 根据需要继续填充其他字段 } // 写入到新的Excel文件 //FileOutputStream fos = new FileOutputStream("D:\\opt"); //workbook.write(fos); 关闭流 //fos.close(); //workbook.close(); // // 将工作簿写入输出流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close(); // 设置响应头 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()); } // 辅助方法:创建单元格并应用样式 private void createCellWithStyle(Row row, int columnIndex, String value, CellStyle style) { Cell cell = row.createCell(columnIndex); cell.setCellValue(value); cell.setCellStyle(style); }
总结
到此这篇关于java自定义填充excel并导出的文章就介绍到这了,更多相关java自定义填充excel并导出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!