1. 依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
2. 代码
2.1 写入excel
/**
* 导出excel
* @param list 数据集合
* @param column 列名
* @param templatePath 模板路径
* @param os 输出流
*/
public static <T> void exportExcel(List<T> list, String[] column, String templatePath, OutputStream os) {
// 获取列名map
Map<String, String> map = XmlParser.getColumnName(templatePath);
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 声明一个单子并命名
HSSFSheet sheet = wb.createSheet("1");
// 给单子名称一个长度
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle style = wb.createCellStyle();
// 创建第一行(也可以称为表头)
HSSFRow row = sheet.createRow(0);
// 样式字体居中
style.setAlignment(HorizontalAlignment.CENTER);
// 给表头第一行一次创建单元格
if (column == null || column.length == 0)
return ;
for (int index