前言
Java中读写Office文件的类库老大莫属Apache POI了,本篇介绍下如何利用POI写入数据到Excel文件。
加入依赖
如果是Maven,加入pom.xml:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
如果是Gradle,加入build.gradle
compile "org.apache.poi:poi:4.1.0" compile "org.apache.poi:poi-ooxml:4.1.0"
生成Excel文件举例,说明写在代码的注释里了
在 POI 中,Workbook类就代表一个 Excel 文件,Sheet 代表一个工作表,Row 代表一列,Cell 代表一个单元格。
public static void main(String[] args) throws Exception {
// 表头
String[] headers = new String[]{"ID", "NAME", "AGE"};
// 数据
List<String[]> datas = new ArrayList<>();
datas.add(new String[]{"1", "张三", "18"});
datas.add(new String[]{"2", "李四", "23"});
Workbook workbook = new XSSFWorkbook();
// 新建一个Sheet
Sheet sheet1 = workbook.createSheet("Sheet1");
// 设置表头的字体
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// 表头居中对齐
headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
// 新建表头的行
Row headerRow = sheet1.createRow(0);
// 新建表头的列,并填充数据
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerCellStyle);
}
// 数据的样式
CellStyle dataCellStyle = workbook.createCellStyle();
// 循环新建数据行、列,并填充数据
int rowNum = 1;
for (String[] data : datas) {
Row row = sheet1.createRow(rowNum++);
for (int j = 0; j < data.length; j++) {
Cell cell = row.createCell(j);
// 设置数据样式为文本,也可以设置为CellType.NUMERIC数字之类的
cell.setCellStyle(dataCellStyle);
cell.setCellValue(data[j]);
}
}
//把workbook保存到文件
FileOutputStream fileOut = new FileOutputStream("/Users/Terry/Downloads/data.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
生成文件用Excel打开如下

如何在Spring/SpringBoot中,生成Excel并提供下载,详见我的博客 https://blog.terrynow.com/2021/02/02/java-spring-springboot-generate-excel-and-download/
如何合并单元格,详见 https://blog.terrynow.com/2021/02/11/apache-poi-merge-cells/
文章评论