参考地址:https://www.cnblogs.com/silenceshining/p/11681924.html
maven:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
代码:
package com.poi;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @describe:
* @date: 2020/9/25
* @TIME: 23:24
*/
public class ExcelTest {
public static void main(String[] args) throws IOException {
testHSSFWorkbook();
}
public static void testHSSFWorkbook() throws IOException {
long start = System.currentTimeMillis();
HSSFWorkbook workbook = new HSSFWorkbook();//创建excel文件(workbook)
//创建一个工作表sheet ”测试工作表1“是这个工作表的名称,也可以不写
HSSFSheet sheet = workbook.createSheet("测试工作表1");
HSSFRow row = sheet.createRow(0);//创建行 从0开始
HSSFCellStyle style = workbook.createCellStyle();//设置单元格样式
//TODO 由于版本问题,新的版本剧中是使用HorizontalAlignment.CENTER水平居中 VerticalAlignment.CENTER垂直居中
//style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
//style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sheet.setDefaultColumnWidth(40);
row.setHeightInPoints(25);
//30个表头
String[] top = new String[30];
//设置表头
for (int i = 0; i < top.length; i++) {
//sheet.setColumnWidth(i,20*256);//第一列设置为20个字符宽度
HSSFCell cell = row.createCell(i);//创建行的单元格,从0开始
cell.setCellValue("表头" + i);//设置单元格内容
cell.setCellStyle(style);
}
System.out.println("准备完表头时间:" + (System.currentTimeMillis() - start));
for (int i = 0; i < 50000; i++) {
HSSFRow rowInfo = sheet.createRow(i + 1);
rowInfo.setHeightInPoints(30);
for (int j = 0; j < 30; j++) {
HSSFCell cellInfo = rowInfo.createCell(j);
cellInfo.setCellValue("列内容为" + j +"----"+format.format(new Date()));
cellInfo.setCellStyle(style);
}
}
System.out.println("准备完表内容时间:" + (System.currentTimeMillis() - start));
FileOutputStream out = new FileOutputStream("D:\\test.xlsx");
workbook.write(out);
out.close();
System.out.println("输入完成时间:" + (System.currentTimeMillis() - start));
System.out.println("finish");
}
}
实现效果:
