创建一个Maven项目
导入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--0.3-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!--0.7-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!--时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
注意 案例皆以0.3版本为例(0.7版本只需要 Workbook workbook = new SXSSFWorkbook();
FileOutputStream outputStream = new FileOutputStream(path + “大数据班分数表07.xlsx”);其他代码不变)
案例一
public static void main(String[] args) throws IOException {
//1 创建工作簿
Workbook workbook = new HSSFWorkbook();
//2 创建表
Sheet sheet = workbook.createSheet("大数据班");
//3 创建第第一行
Row row = sheet.createRow(0);
//4 创建 第一个单元格(1,1)
Cell cell = row.createCell(0);
// 第一个格子填入的数据
cell.setCellValue("三天的学习成绩平均分:");
Cell cell1 = row.createCell(1);
// 第二个格子填入的数据
cell1.setCellValue("89");
//创建第二行数据(2,1)
Row row1 = sheet.createRow(1);
//4 创建 第一个单元格(2,1)
Cell cell2 = row1.createCell(0);
// 第一个格子填入的数据
cell2.setCellValue("统计时间:");
Cell cell3 = row1.createCell(1);
// 第二个格子填入的数据
String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
cell3.setCellValue(time);
// 生成表(io 流)
FileOutputStream outputStream = new FileOutputStream(path + "大数据班分数表03.xls");
//输出
workbook.write(outputStream);
outputStream.close();
System.out.println("生成完成!");
}
生成文件
案例二
private static String path = "src/main/java";
public static void main(String[] args) throws IOException {
long begin = System.currentTimeMillis();
//创建一个工作簿
Workbook workbook = new HSSFWorkbook();
//创建表
Sheet sheet = workbook.createSheet();
for(int i=0;i<65536;i++){
Row row = sheet.createRow(i);
for(int j=0;j<10;j++){
Cell cell = row.createCell(j);
cell.setCellValue(j);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(path+"data.xls");
//输出
workbook.write(fileOutputStream);
fileOutputStream.close();
long end = System.currentTimeMillis();
System.out.println("执行所花费的时间:"+(double)(end-begin)/1000);
}
效果图
注意:0.3版本最多有65563行数据
0.7版本你可认为有无数行,前者速度快后者慢