MyExcel 是一個集導入、導出、加密 Excel 等多項功能的 Java 工具包。
本次更新如下:
更多請移步:https://github.com/liaochong/myexcel/wik
導出:
/**
* 方式一:普通方式導出
*/
@GetMapping("/default/excel/example")
public void defaultBuild(HttpServletResponse response) throws Exception {
List<ArtCrowd> dataList = this.getDataList();
Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
.build(dataList);
AttachmentExportUtil.export(workbook, "藝術生信息", response);
// 加密導出 AttachmentExportUtil.encryptExport(workbook, "藝術生信息", response,"123456");
}
/**
* 方式二:生產者消費者模式導出,分批獲取數據,分批寫入Excel,真正意義上實現海量數據導出
*/
@GetMapping("/default/excel/stream/example")
public void streamBuild(HttpServletResponse response) throws Exception {
// 顯式標明開始構建
DefaultStreamExcelBuilder defaultExcelBuilder = DefaultStreamExcelBuilder.of(ArtCrowd.class)
.threadPool(Executors.newFixedThreadPool(10))
.start();
// 多線程非同步獲取數據並追加至excel,join等待線程執行完成
List<CompletableFuture> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
CompletableFuture future = CompletableFuture.runAsync(() -> {
List<ArtCrowd> dataList = this.getDataList();
// 數據追加
defaultExcelBuilder.append(dataList);
});
futures.add(future);
}
futures.forEach(CompletableFuture::join);
// 最終構建
Workbook workbook = defaultExcelBuilder.build();
AttachmentExportUtil.export(workbook, "藝術生信息", response);
}
導入:
URL htmlToExcelEampleURL = this.getClass().getResource("/templates/read_example.xlsx");
Path path = Paths.get(htmlToExcelEampleURL.toURI());
// 方式一:全部讀取后處理
List<ArtCrowd> result = DefaultExcelReader.of(ArtCrowd.class)
.sheet(0) // 0代表第一個,如果為0,可省略該操作
.rowFilter(row -> row.getRowNum() > 0) // 如無需過濾,可省略該操作,0代表第一行
.beanFilter(ArtCrowd::isDance) // bean過濾
.read(path.toFile());// 可接收inputStream
// 方式二:讀取一行處理一行,可自行決定終止條件
DefaultExcelReader.of(ArtCrowd.class)
.sheet(0) // 0代表第一個,如果為0,可省略該操作
.rowFilter(row -> row.getRowNum() > 0) // 如無需過濾,可省略該操作,0代表第一行
.beanFilter(ArtCrowd::isDance) // bean過濾
.readThen(path.toFile() ,artCrowd -> System.out.println(artCrowd.getName));// 可接收inputStream
// 方式三:全部讀取后處理,SAX模式,避免OOM,建議大量數據使用
List<ArtCrowd> result = SaxExcelReader.of(ArtCrowd.class)
.sheet(0) // 0代表第一個,如果為0,可省略該操作
.rowFilter(row -> row.getRowNum() > 0) // 如無需過濾,可省略該操作,0代表第一行
.beanFilter(ArtCrowd::isDance) // bean過濾
.read(path.toFile());// 可接收inputStream
// 方式四:讀取一行處理一行,可自行決定終止條件,SAX模式,避免OOM,建議大量數據使用
SaxExcelReader.of(ArtCrowd.class)
.sheet(0) // 0代表第一個,如果為0,可省略該操作
.rowFilter(row -> row.getRowNum() > 0) // 如無需過濾,可省略該操作,0代表第一行
.beanFilter(ArtCrowd::isDance) // bean過濾
.readThen(path.toFile() ,artCrowd -> System.out.println(artCrowd.getName));// 可接收inputStream
public class ArtCrowd {
// index代表列索引,從0開始
@ExcelColumn(index = 0)
private String name;
@ExcelColumn(index = 1)
private String age;
@ExcelColumn(index = 2,dateFormatPattern="yyyy-MM-dd")
private Date birthday;
}
效果:
[admin
]