以execl格式导出账单列表

这个过程主要分为数据处理、Excel文件生成、文件响应给客户端等关键步骤。

1. 准备数据源

首先获取要导出的账单数据,从数据库中查询数据并将其封装为对象列表(如List)。每个对象代表一条账单记录,字段包含账单日期、金额等。

List<Bill> billList = billService.getAllBills();

2. 使用Apache POI库生成Excel文件

Apache POI库是Java中最常用的处理Excel文件的工具。可以通过创建工作簿(Workbook)、工作表(Sheet)、行(Row)和单元格(Cell)来生成Excel文件。

主要步骤:

  1. 添加Apache POI依赖
    pom.xml中添加POI依赖:

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.0.0</version>
    </dependency>
    
  2. 创建Excel工作簿和工作表
    使用XSSFWorkbook创建一个工作簿,然后创建一个工作表:

    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Bill List");
    
  3. 设置标题行
    设置Excel文件的标题行(表头):

    Row headerRow = sheet.createRow(0);
    String[] headers = {"xx", "xx", "xx", "xx"};
    for (int i = 0; i < headers.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(headers[i]);
    }
    
  4. 填充账单数据
    遍历账单列表,将每个账单信息填入Excel的行中:

    int rowNum = 1;
    for (Bill bill : billList) {
        Row row = sheet.createRow(rowNum++);
        row.createCell(0).setCellValue(bill.getId());
        row.createCell(1).setCellValue(bill.getDate().toString());
        row.createCell(2).setCellValue(bill.getAmount());
        row.createCell(3).setCellValue(bill.getCustomerName());
        row.createCell(4).setCellValue(bill.getStatus());
    }
    
  5. 自动调整列宽
    设置列宽自适应,以提高可读性:

    for (int i = 0; i < headers.length; i++) {
        sheet.autoSizeColumn(i);
    }
    

3. 将Excel文件写入输出流

在Java Web环境中,通常将Excel文件通过HTTP响应流传递给客户端。

  1. 设置响应头
    设置HTTP响应头,定义文件类型、文件名等信息:

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=BillList.xlsx");
    
  2. 将Excel文件写入响应输出流
    将Excel工作簿内容写入到ServletOutputStream中,使客户端能下载此文件:

    try (ServletOutputStream out = response.getOutputStream()) {
        workbook.write(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        workbook.close();
    }
    
posted @ 2024-10-31 15:08  Uiui·  阅读(91)  评论(0)    收藏  举报