一、Maven依赖
<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>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
二、代码示例
/**
* @param tableData 文件数据信息
* @return 文件输入流信息
*/
// 创建一个Excel文件并填充数据,返回一个InputStream
private InputStream createImageTextExcelFile(List<List<String>> tableData) {
// 创建一个新的Excel工作簿
try (Workbook workbook = new XSSFWorkbook();
// 创建一个字节输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// 创建一个名为Sheet1的工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表格标题行
// 创建第一行
Row titleRow = sheet.createRow(0);
// 创建标题单元格样式
CellStyle titleCellStyle = workbook.createCellStyle();
// 设置标题样式为水平居中
titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
// 创建字体样式
Font titleFont = workbook.createFont();
// 设置字体为粗体
titleFont.setBold(true);
// 设置字体大小
titleFont.setFontHeightInPoints((short) 14);
// 将字体样式应用到标题单元格样式
titleCellStyle.setFont(titleFont);
// 在标题行创建一个单元格
Cell titleCell = titleRow.createCell(0);
// 设置单元格内容
titleCell.setCellValue("数据表格第一行标题信息");
// 应用标题单元格样式
titleCell.setCellStyle(titleCellStyle);
// 合并单元格(标题跨越六列)
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
// 创建表头行
// 创建第二行作为表头
Row headerRow = sheet.createRow(1);
List<String> headers = Arrays.asList("列1", "列2", "列3", "列4", "列5", "列6");
// 遍历表头内容
for (int i = 0; i < headers.size(); i++) {
// 创建表头单元格
Cell headerCell = headerRow.createCell(i);
// 设置表头单元格内容
headerCell.setCellValue(headers.get(i));
}
// 填充数据内容
// 遍历数据行
for (int i = 0; i < tableData.size(); i++) {
// 创建数据行
Row dataRow = sheet.createRow(i + 2);
// 获取一行数据
List<String> rowData = tableData.get(i);
// 遍历一行数据的每个单元格
for (int j = 0; j < rowData.size(); j++) {
// 创建数据单元格
Cell dataCell = dataRow.createCell(j);
// 设置数据单元格内容
dataCell.setCellValue(rowData.get(j));
}
}
// 将工作簿内容写入输出流
workbook.write(outputStream);
// 将输出流转换为输入流并返回
return new ByteArrayInputStream(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
// 发生异常时返回null
return null;
}