原因:公司里别的部门提供的jar包,接口方法按照传参老是报错,网上也没有详细的解释原因,所以通过debug发现问题的所在,是因为少设置参数。
params.setTemplateUrl("classpath:student_template.xlsx");
params.setScanAllsheet(false);
params.setColForEach(true);
params.setScanAllsheet(true);
params.setSheetNum(new int[] {0, 1});
如果报错空指针异常,有可能是因为样式未制定,可以设置样式,如下:
// 设置列宽
Map<String, ExcelExportEntityColWidth> colWidthMap = new HashMap<>();
colWidthMap.put("id", new ExcelExportEntityColWidth(15));
colWidthMap.put("name", new ExcelExportEntityColWidth(20));
colWidthMap.put("dept", new ExcelExportEntityColWidth(25));
colWidthMap.put("position", new ExcelExportEntityColWidth(30));
// 设置样式
ExcelExportStylerColorImpl styler = new ExcelExportStylerColorImpl();
styler.setTableHeaderColor((short) 13);
styler.setTableContentColor((short) 11);
params.setStyler(styler);
下面是比较完整的流程
public class ExportExcel {
public static void main(String[] args) {
// 准备数据模型
Map<Integer, Map<String, Object>> dataMap = new HashMap<>();
Map<String, Object> data1 = new HashMap<>();
data1.put("className", "Class 1");
List<Student> students1 = new ArrayList<>();
students1.add(new Student("Tom", 12, "Male"));
students1.add(new Student("Jerry", 11, "Male"));
data1.put("students", students1);
dataMap.put(0, data1);
Map<String, Object> data2 = new HashMap<>();
data2.put("className", "Class 2");
List<Student> students2 = new ArrayList<>();
students2.add(new Student("Lucy", 13, "Female"));
students2.add(new Student("Lily", 12, "Female"));
data2.put("students", students2);
dataMap.put(1, data2);
// 准备模板导出参数
TemplateExportParams params = new TemplateExportParams();
params.setScanAllsheet(false);
params.setColForEach(true);
params.setScanAllsheet(true);
params.setSheetNum(new int[] {0, 1});
// 创建Workbook对象并导出Excel
Workbook workbook = new ExcelExportService().createExcleByTemplate(params, dataMap);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("student_export.xlsx");
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// 省略getter和setter
}