自学内容网 自学内容网

java 自定义填充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);
    }

以上仅供学习参考!!!


原文地址:https://blog.csdn.net/weixin_60948956/article/details/142791926

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!