?一 使用alibaba開源的 easyexcel框架,后臺只需一個工具類即可實現下載
后端下載實現
? 依賴 pom.xml
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.0</version></dependency>
后臺JAVA代碼
/*** 下載xls數據* @param params* @param response* @throws IOException*/@PostMapping("/exportData")public void exportData(@RequestBody String params, HttpServletResponse response) throws IOException {JSONObject query = JSONObject.parseObject(params);String beginTime = query.getString("beginDate");String endTime = query.getString("endDate");List<AliIotLog> resultList = new ArrayList<>();//查詢業務數據列表 resultList WebDownloadUtil.downloadXlsByList(response, resultList,LogExport.class,"xls");}
一個 java bean代碼,用于設置導出時的列映射顯示名稱關系
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import java.io.Serializable;
import java.time.LocalDateTime;@ContentRowHeight(20)//注解用于指定某元素的內容行高度為20。
@HeadRowHeight(20)//注解用于指定某元素的表頭行高度為20。
@ColumnWidth(30) //注解用于指定某元素的列寬度為30。
public class LogExport implements Serializable {private static final long serialVersionUID = 1L;/*** 設備協議內容*/@ExcelProperty("接收報文")private String inHexStr;/*** 回復內容*/@ExcelProperty("發送報文")private String outHexStr;/*** 地址或通道*/@ExcelProperty("地址")private String addr;/*** 時間*/@ExcelProperty("時間")private LocalDateTime ctime;public String getInHexStr() {return inHexStr;}public void setInHexStr(String inHexStr) {this.inHexStr = inHexStr;}public String getOutHexStr() {return outHexStr;}public void setOutHexStr(String outHexStr) {this.outHexStr = outHexStr;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}public LocalDateTime getCtime() {return ctime;}public void setCtime(LocalDateTime ctime) {this.ctime = ctime;}}
?完整下載工具類代碼
/*** web 下載文件封裝* @author hua* @date 2024-07-06 14:30*/
public class WebDownloadUtil {/*** 下載文件* @param response* @param resultList 列表數據* @param clazz 類形* @param format 表格格式 xlx xlsx csv* @throws IOException*/public static void downloadXlsByList(HttpServletResponse response, List resultList,Class clazz,String format) throws IOException {response.setContentType("application/vnd.ms-excel");response.setHeader("content-disposition","attachment;filename=data_export.xls");//下載文件名稱在前端vue頁面處理ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.CSV;if("xls".equals(format)){excelTypeEnum = ExcelTypeEnum.XLS;}else if("xlsx".equals(format)){excelTypeEnum = ExcelTypeEnum.XLSX;}ExcelWriterBuilder writeWork = EasyExcel.write(response.getOutputStream(),clazz ).excelType(excelTypeEnum).registerConverter(new Converter<LocalDateTime>(){public String format = "yyyy-MM-dd HH:mm:ss";@Overridepublic Class<LocalDateTime> supportJavaTypeKey() {return LocalDateTime.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}@Overridepublic LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(format)).atStartOfDay();}@Overridepublic WriteCellData<?> convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {if(localDateTime==null){return new WriteCellData<>("");}DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);String format = formatter.format(localDateTime);return new WriteCellData(format);}});ExcelWriterSheetBuilder sheet = writeWork.sheet();sheet.doWrite(resultList);}
}
前端vue下載實現
vue前端頁下載調用按鈕
import webUtil from "@api/webUtil";export default {name: 'sys_log',data () {return {queryBody:{},list:[],
}methods: {exportExcel () {//單擊下載console.log('query data',this.queryBody)let url='/xxx/xxx/xxxx';webUtil.downloadXls(url,this.queryBody,"導出數據")}}}
vue 完整下載工具類
import request from '@/plugins/request';const webUtil= {downloadXls:function(url,data, fileNamePrefix){request({url: url,method: 'post',responseType: "blob",data}).then(data => {let blob = new Blob([data], {type: 'application/x-msdownload;charset=UTF-8'});let fileName = fileNamePrefix + Date.parse(new Date()) + '.xls';if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob, fileName);} else {let link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = fileName;link.click();window.URL.revokeObjectURL(link.href);}}).catch(error => {console.error('Error exporting and downloading data:', error);}));}};
export default webUtil;