EasyExcel基本操作看这一篇文章就够了
EasyExcel是一个为了简化Excel操作,而封装的一个Java库。以下是一些基本操作的示例代码:
- 写入Excel:
import com.alibaba.excel.EasyExcel;
public class WriteExcel {
public static void main(String[] args) {
String fileName = "example.xlsx";
EasyExcel.write(fileName, DemoData.class)
.sheet("Sheet1")
.doWrite(getData());
}
private static List<DemoData> getData() {
List<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new DemoData(i, "Name" + i));
}
return list;
}
}
class DemoData {
@ExcelProperty("序号")
private int number;
@ExcelProperty("名称")
private String name;
public DemoData(int number, String name) {
this.number = number;
this.name = name;
}
// getters and setters
}
- 读取Excel:
import com.alibaba.excel.EasyExcel;
public class ReadExcel {
public static void main(String[] args) {
String fileName = "example.xlsx";
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
}
}
class DemoDataListener extends AnalysisEventListener<DemoData> {
@Override
public void invoke(DemoData data, AnalysisContext context) {
System.out.println("Number: " + data.getNumber() + ", Name: " + data.getName());
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) { }
}
- 修改Excel样式:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
public class StyleExcel {
public static void main(String[] args) {
String fileName = "example.xlsx";
WriteSheet writeSheet = EasyExcel.writeSheet(0, "Sheet1")
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
EasyExcel.write(fileName, DemoData.class)
.sheet(writeSheet)
.doWrite(getData());
}
private static List<DemoData> getData() {
// ... same as before
}
}
这些示
评论已关闭