用java语言,写一段easypoi导出为excel的示例,要求自定义列名,列数随着字段值name的数据的个数增多
时间: 2024-06-10 15:07:55 浏览: 101
easypoi导入导出excel表格.pdf
好的,我可以为你提供相关的示例代码:
```java
// 导出excel
public static void exportExcel(List<User> userList, HttpServletResponse response) {
try {
// 定义excel文件名
String fileName = "userList_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/vnd.ms-excel");
// 自定义列名
List<CustomerExcelProperty> excelProperties = new ArrayList<>();
int i = 0;
for (String name : userList.get(0).getName().split(",")) {
CustomerExcelProperty excelProperty = new CustomerExcelProperty();
excelProperty.setIndex(++i);
excelProperty.setName(name);
excelProperty.setMethod("getName");
excelProperties.add(excelProperty);
}
// 设置excel字段信息
List<ExcelExportEntity> exportFields = excelProperties.stream().map(property -> {
ExcelExportEntity exportEntity = new ExcelExportEntity(property.getName(), property.getName());
exportEntity.setMethod(property.getMethod());
exportEntity.setFormat(property.getFormat());
exportEntity.setWidth(16);
exportEntity.setHeight(14);
exportEntity.setReplace(null);
exportEntity.setMergeVertical(false);
exportEntity.setMergeHorizontal(false);
exportEntity.setWrap(false);
exportEntity.setShrinkToFit(false);
exportEntity.setOrderNum(property.getIndex());
return exportEntity;
}).collect(Collectors.toList());
// 执行导出
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息", "用户信息"), exportFields, userList);
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
// 用户实体类
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
// 自定义列属性类
public class CustomerExcelProperty {
private int index;
private String name;
private String method;
private String format;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
```
希望这个示例可以帮助到你!
阅读全文