Java操作Excel

本文介绍了Java中使用Apache POI和EasyExcel操作Excel的常见场景,包括POI的HSSF、XSSF和SXSSF在数据批量导入时的优缺点,以及EasyExcel的简单使用,如导入依赖、写入和读取测试。
摘要由CSDN通过智能技术生成

1、POI和EasyExcel

1.1 常用场景

  1. 将用户信息导出为Excel表格(导出数据…)
  2. 将Excel表中的信息录入到网站数据库(习题上传…)

操作Excel目前比较流行的就是 Apache POI 和阿里巴巴的 EasyExcel

Apache POI

Apache POI官网: http://poi.apache.org/

  • HSSF: 提供读写Excel格式的功能
  • XSSF: 提供读写Excel OOXML格式的功能
  • HWPF: 提供读写Word格式的功能
  • HSLF: 提供读写PowerPoint格式的功能
  • HDGF: 提供读写Visio格式的功能

EasyExcel

EasyExcel官网: https://github.com/alibaba/easyexcel

2、POI-Excel写

2.1 创建项目

  1. 建立一个空项目,创建普通Maven的Moudle

  2. 引入pom依赖

    <dependencies>
        <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>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
    
  • 工作簿
  • 工作表

xls版本

@Test
public void testWrite03() throws Exception {
   
    // 1.创建一个工作簿
    Workbook workbook = new HSSFWorkbook();
    // 2.创建一个工作表
    Sheet sheet = workbook.createSheet("用户信息表");
    // 3.创建一行 (1,1)
    Row row1 = sheet.createRow(0);
    // 4.创建一个单元格
    Cell cell11 = row1.createCell(0);
    cell11.setCellValue("用户名");
    // (1,2)
    Cell cell12 = row1.createCell(1);
    cell12.setCellValue("日期");
    // 第二行(2,1)
    Row row2 = sheet.createRow(1);
    Cell cell21 = row2.createCell(0);
    cell21.setCellValue("admin");
    // (2,2)
    Cell cell22 = row2.createCell(1);
    String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    cell22.setCellValue(time);
    // 生成一张表(IO流) 03版本使用xls结尾
    FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户信息表.xls");
    // 输出
    workbook.write(fileOutputStream);
    // 关闭流
    fileOutputStream.close();
    System.out.println("用户信息表生成成功!");
}

xlsx版本

@Test
public void testWrite07() throws Exception {
   
    // 1.创建一个工作簿
    Workbook workbook = new XSSFWorkbook();
    // 2.创建一个工作表
    Sheet sheet = workbook.createSheet("用户信息表");
    // 3.创建一行 (1,1)
    Row row1 = sheet.createRow(0);
    <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值