導(dǎo)出
ExcelUtil將Excel寫(xiě)出封裝為ExcelWriter静袖,原理為包裝了Workbook對(duì)象,每次調(diào)用merge(合并單元格)或者write(寫(xiě)出數(shù)據(jù))方法后只是將數(shù)據(jù)寫(xiě)入到Workbook,并不寫(xiě)出文件徐绑,只有調(diào)用flush或者close方法后才會(huì)真正寫(xiě)出文件。
由于機(jī)制原因莫辨,在寫(xiě)出結(jié)束后需要關(guān)閉ExcelWriter對(duì)象傲茄,調(diào)用close方法即可關(guān)閉,此時(shí)才會(huì)釋放Workbook對(duì)象資源沮榜,否則帶有數(shù)據(jù)的Workbook一直會(huì)常駐內(nèi)存盘榨。
獲取導(dǎo)出ExcelWriter對(duì)象ExcelUtil.getWriter()
getWriter()有幾個(gè)重載方法
/**
* destFile 目標(biāo)文件
* sheetName sheet表名
*/
getWriter(File destFile, String sheetName)
/**
* destFilePath 目標(biāo)文件路徑
* sheetName sheet表名
*/
getWriter(String destFilePath, String sheetName)
/**
* destFile 目標(biāo)文件
*/
getWriter(File destFile)
/**
* destFilePath 目標(biāo)文件路徑
*/
getWriter(String destFilePath)
導(dǎo)出到固定磁盤(pán)位置
@PostMapping("/export")
public Result<String> exportData(@RequestBody List<Map<String, Object>> dataList) {
if (CollUtil.isNotEmpty(dataList)) {
// 通過(guò)hutool工具類創(chuàng)建writer,默認(rèn)創(chuàng)建xls格式
ExcelWriter writer = ExcelUtil.getWriter("E:\test\test.xls");
//將list map數(shù)據(jù)寫(xiě)出文件
writer.write(dataList, true);
writer.close();
} else {
return ResultUtil.failure("表無(wú)數(shù)據(jù)蟆融!");
}
}
以response流的方式輸出
@PostMapping("/exportData")
public Result<String> exportDataForExcel(@RequestBody List<Map<String, Object>> dataList,HttpServletResponse response) throws IOException {
if (CollUtil.isNotEmpty(dataList)) {
// 通過(guò)工具類創(chuàng)建writer草巡,默認(rèn)創(chuàng)建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
writer.write(dataList, true);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=test.xls");
ServletOutputStream out = response.getOutputStream();
writer.flush(out);
writer.close();
return null;
} else {
return ResultUtil.failure("表無(wú)數(shù)據(jù)!");
}
讀取excel內(nèi)容
讀取Excel內(nèi)容的封裝型酥,通過(guò)構(gòu)造ExcelReader對(duì)象山憨,指定被讀取的Excel文件查乒、流或工作簿,然后調(diào)用readXXX方法讀取內(nèi)容為指定格式郁竟。
讀取excel內(nèi)容的其他read方法
/**
* startRowIndex 起始行(包含玛迄,從0開(kāi)始計(jì)數(shù))
*/
read(int startRowIndex);
/**
* startRowIndex 起始行(包含,從0開(kāi)始計(jì)數(shù))
* endRowIndex 讀取結(jié)束行(包含棚亩,從0開(kāi)始計(jì)數(shù))
*/
read(int startRowIndex, int endRowIndex);
/**
* startRowIndex 起始行(包含蓖议,從0開(kāi)始計(jì)數(shù))
* endRowIndex 結(jié)束行(包含,從0開(kāi)始計(jì)數(shù))
* aliasFirstLine 是否首行作為標(biāo)題行轉(zhuǎn)換別名
*/
read(int startRowIndex, int endRowIndex, boolean aliasFirstLine);
/**
* beanType 每行對(duì)應(yīng)Bean的類型
*/
readAll(Class<T> beanType);
讀取為Map列表
private List<Map<String,Object>> readerExcelInfo(String excelUrl){
List<Map<String,Object>> result = new ArrayList<>();
if(excelUrl.isEmpty()){
return Collections.emptyList();
}
try {
ExcelReader excelReader = ExcelUtil.getReader(new File(excelUrl));
//讀取為Map列表讥蟆,默認(rèn)第一行為標(biāo)題行勒虾,Map中的key為標(biāo)題,value為標(biāo)題對(duì)應(yīng)的單元格值瘸彤。
result = excelReader.readAll();
}catch (Exception e){
e.printStackTrace();
}
return result;
}