ApachePOI入门案例——向Excel文件写入内容

依赖

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

解决上述依赖警告问题

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.22</version>
</dependency>

案例

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {
        write();
    }

    public static void write() throws IOException {

        //在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();

        //在Excel文件中创建一个Sheet页
        XSSFSheet sheet = excel.createSheet("demo");

        //在Sheet页中创建行对象
        XSSFRow row = sheet.createRow(1);

        //创建单元格并且写入内容
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("性别");

        //再创建一个行
        row = sheet.createRow(2);
        //创建单元格并且写入内容
        row.createCell(1).setCellValue("艾伦");
        row.createCell(2).setCellValue("男");

        //再创建一个行
        row = sheet.createRow(3);
        //创建单元格并且写入内容
        row.createCell(1).setCellValue("三笠");
        row.createCell(2).setCellValue("女");

        //将Excel文件从内存写入磁盘
        FileOutputStream output = new FileOutputStream("D:\\develop\\demo.xlsx");
        excel.write(output);

        //关闭资源
        output.close();
        excel.close();
    }
}

查看结果

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值