1. 引入依赖:
<!--EasyPoi导入导出-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
2.上代码:
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* easypoi
*
* @author zero
* @review_date 2022-08-19
*/
public class TestEasyExcel {
public static void main(String[] args) throws Exception {
// 格式为每行都是 张三========>12========>20220101
/*
张三========>12========>20220101
李四========>22========>20220102
王五========>32========>20220103
*/
List<String> txtList = Files.readAllLines(Paths.get("C:\\Users\\Administrator\\Desktop\\1.txt"));
List<ExcelInfo> list = new ArrayList<>();
if (txtList.size() <= 0) {
System.err.println("txt中没有数据,直接退出!!!");
return;
}
for (String line : txtList) {
if (line != null && !"".equals(line)) {
line = line.trim();
if (!"".equals(line)) {
String[] tmp1 = line.split("========>");
String name = tmp1[0];
int age = Integer.parseInt(tmp1[1]);
String date = tmp1[2];
ExcelInfo excelInfo = new ExcelInfo();
excelInfo.setName(name);
excelInfo.setAge(age);
excelInfo.setDate(date);
list.add(excelInfo);
}
}
}
makeExcel(ExcelInfo.class, list, "C:\\Users\\Administrator\\Desktop\\", "target1.xls");
}
private static void makeExcel(Class<?> pojoClass, Collection<?> dataSet, String path, String filename) throws IOException {
File saveFile = new File(path);
if (!saveFile.exists()) {
boolean makeFilesBl = saveFile.mkdirs();
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, dataSet);
try (FileOutputStream fos = new FileOutputStream(path + filename);) {
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
}
static class ExcelInfo {
@Excel(name = "name", width = 80)
private String name;
@Excel(name = "age", width = 80)
private int age;
@Excel(name = "date", width = 80)
private String date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
}