前言
功能:将数据库中的数据导出到Excel,将Excel中的数据导入导数据库。
提示:原始POI的方式比较繁琐,不想看的可以跳过,直接看方式二,使用阿里巴巴帮我们封装好POI的easyExcel
一、03版Excel和07版Excel的区别
具体两者有哪些区别,请参考https://wenku.baidu.com/view/6c592a97f524ccbff1218477.html
这里只关注比较重要的两点:
03版本的Excel是xls文件,07版本的Excel是xlsx文件
03版最多可以放65536行数据,而07版可以存放100多万行。
数据量的大小决定着采用哪种方式进行数据的导入导出。POI提供了以下三种WorkBook实现类:
(1)HSSF
优点:是过程中写入缓存、不操作磁盘,最后一次性写入磁盘,速度快
缺点:最多只能处理65536行数据,操作xls类型(03)
(2)XSSF
优点:可以写较大的数据量,如20万行数据(比起HSFF多了不少)
缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万行数据的时候
(3)SXSSF
优点:XSSF的升级版,可以写非常大的数据量,如100万条甚至更多条,写数据速度快,占用更少的内存。
需要注意的就是,过程中会产生临时文件,需要清理。
好了,读到这里,你只需要知道什么类型的Excel选用什么类型的WorkBook实现类即可
二、方式一:POI
首先第一步就是要导入所需要的依赖
其中joda.time和Junit依赖非必须导入,只是便于我们接下来的测试
<!-- xls(03)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<!-- xls(07)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<!-- 日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<!-- test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
1.导出
1.1 导出单行数据
public class ExcelWriteTest {
String PATH = "D:\\yzh1024Project\\car_system\\";
@Test
public void test03() throws Exception {
//1、创建一个工作簿
Workbook workbook = new HSSFWorkbook();
//2、创建一个工作表
Sheet sheet = workbook.createSheet("统计表");
//3、创建一个行
Row row1 = sheet.createRow(0);
//4、创建单元格
Cell cell00 = row1.createCell(0);
cell00.setCellValue("hahah");
Cell cell01 = row1.createCell(1);
cell01.setCellValue(666);
Row row2 = sheet.createRow(1);
//再创建一行
Cell cell10 = row2.createCell(0);
cell10.setCellValue("时间:");
Cell cell11 = row2.createCell(1);
String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
cell11.setCellValue(time);
//生成一张表
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "统计表.xls");
//输出
workbook.write(fileOutputStream);
//关闭流
fileOutputStream.close();
System.out.println("文件生成完毕");
}
}