Java 导出Excel报表

这篇博客介绍了如何在Java项目中利用Apache POI库导出Excel报表,包括在Maven项目中添加相关依赖,以及提供保存到本地和通过Web端下载的代码示例。

首先在maven项目中添加依赖

 <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>4.0.1</version>
 </dependency>

保存到本地文件代码示例:

 public void test() throws IOException {
 		// 创建 excel 对象
        XSSFWorkbook sheets = new XSSFWorkbook();
        // 创建 excel 页(一个 excel 是可以有多个页的)
        XSSFSheet sheet = sheets.createSheet();
        // 创建行,数字表示索引,从0开始,1表示第二行
        XSSFRow row = sheet.createRow(1);
        // 在行中指定列,数字表示索引,从0开始,1表示第二列
        XSSFCell cell = row.createCell(1);
        // 在列中写入数据
        cell.setCellValue("hello excel!");
        // 创建文件对象
        File file = new File("test.xlsx");
        // 创建写入到文件的流
        FileOutputStream out = new FileOutputStream(file);
        // 将 excel 数据写入文件中
        sheets.write(out);
        // 关闭 excel 流
        sheets.close();
        // 关闭文件流
        out.close();
    }

web端下载代码示例:

public void test() throws IOException {
 		XSSFWorkbook sheets = new XSSFWorkbook();
        sheets.createSheet();
        XSSFRow row = first.createRow(1);
        XSSFCell cell = row.createCell(1);
        cell.setCellValue("hello excel!");
        // 解决文件名中文乱码
        String fileName = new String("测试.xlsx".getBytes(), "iso-8859-1");
        // 设置 content-type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 设置 http 响应头
        response.addHeader("content-disposition", "attachment;fileName=" + fileName);
        // 获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 将数据写入响应流
        sheets.write(outputStream);
        outputStream.flush();
        // 关闭流
        sheets.close();
        outputStream.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值