使用Apache POI将数据写入Excel文件

2024-01-08 09:29:14

首先导入依赖

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

其次写个测试类

public class ExcelTest {
    /**
     * 基于POI向Excel文件写入数据
     * @throws Exception
     */
    public static void write() throws Exception{
        //在内存中创建一个Excel文件对象
        XSSFWorkbook excel = new XSSFWorkbook();
        //创建Sheet页
        XSSFSheet sheet = excel.createSheet("rejiao");

        //在Sheet页中创建行,0表示第1行
        XSSFRow row1 = sheet.createRow(0);

        //创建单元格并在单元格中设置值,单元格编号也是从0开始,1表示第2个单元格
        row1.createCell(0).setCellValue("pushId");

        for (int i = 0; i < 9999; i++) {
            XSSFRow row2 = sheet.createRow(i+1);
            row2.createCell(0).setCellValue("push" + (10000 + i));
        }



        FileOutputStream out = new FileOutputStream(new File("D:\\rejiao.xlsx"));
        //通过输出流将内存中的Excel文件写入到磁盘上
        excel.write(out);

        //关闭资源
        out.flush();
        out.close();
        excel.close();
    }
    public static void main(String[] args) throws Exception {
        write();
    }
}

效果展示
在这里插入图片描述

文章来源:https://blog.csdn.net/aaaaaaaaattt/article/details/135398380
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。