java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java自定义填充excel并导出

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 {

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);
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); // ... (创建并填充其他单元格) }

5. 写入输出流并返回响应

ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
workbook.write(outputStream); workbook.close();
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());

将 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并导出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文