文章目录
- esayExcel
- 导出
- 依赖
- 后端代码
- controller
- service
- 单元格宽度配置类
- util
- 前端代码
- 若依
- 配置多数据源
esayExcel
导出
依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.4</version>
</dependency>
后端代码
controller
@RequestMapping("/exportDemo")
public void exportDemo(@RequestBody Map<String, String> params,HttpServletResponse response) {testService.exportDemo(params, response);
}
service
public void exportDemo(Map<String, String> params,HttpServletResponse response) {List<Map<String, Object>> dataList = getDataList(params);try {response.reset();response.setHeader("Content-type", "application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode("表名称-" +DateUtils.format(new Date(),"yyyyMMddHHmmss") + ".xls", "utf-8"));// 表内容样式WriteCellStyle writeCellStyleContent = new WriteCellStyle();//垂直居中,水平居中writeCellStyleContent .setVerticalAlignment(VerticalAlignment.CENTER);writeCellStyleContent .setHorizontalAlignment(HorizontalAlignment.CENTER);writeCellStyleContent .setBorderLeft(BorderStyle.THIN);writeCellStyleContent .setBorderTop(BorderStyle.THIN);writeCellStyleContent .setBorderRight(BorderStyle.THIN);writeCellStyleContent .setBorderBottom(BorderStyle.THIN);//设置 自动换行writeCellStyleContent .setWrapped(true);WriteFont writeFont = new WriteFont();writeFont.setFontHeightInPoints((short) 12);writeFont.setFontName("宋体");writeCellStyleContent.setWriteFont(writeFont);//表头样式WriteCellStyle writeCellStyleHead = new WriteCellStyle();writeFont = new WriteFont();writeFont.setFontHeightInPoints((short) 12);writeFont.setBold(true);writeFont.setFontName("宋体");writeCellStyleHead.setWriteFont(writeFont);ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();List<List<String>> head = new ArrayList<List<String>>() {{add(new ArrayList<String>() {{add("单位单位单位");}});add(new ArrayList<String>() {{add("语文");add("已");}});add(new ArrayList<String>() {{add("数学");add("未");}});add(new ArrayList<String>() {{add("时间");}});}};WriteSheet ajSheet1 = EasyExcel.writerSheet(0, "sheetName").head(head).registerWriteHandler(new ExcelWidthStyleStrategy()).registerWriteHandler(new HorizontalCellStyleStrategy(writeCellStyleHead,writeCellStyleContent)).build();writer.write(getData(dataList), ajSheet1);writer.finish();} catch (IOException e) {e.printStackTrace();}
}
单元格宽度配置类
package com.utils;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.util.CollectionUtils;import java.util.HashMap;
import java.util.List;
import java.util.Map;public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {private Map<Integer, Map<Integer,Integer>> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder,List<CellData> list, Cell cell, Head head,Integer integer, Boolean aBoolean) {boolean needSetWidth = aBoolean || !CollectionUtils.isEmpty(list);int columnIndex = cell.getColumnIndex();if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap= CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap<>();CACHE.put(writeSheetHolder.getSheetNo(),maxColumnWidthMap);}Integer columnWidth = dataLength(list, cell, aBoolean);if (columnWidth >=0) {if (columnWidth > 150) {columnWidth = 150;}Integer maxColumnWidth = maxColumnWidthMap.get(columnIndex);if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(columnIndex,columnWidth);writeSheetHolder.getSheet().setColumnWidth(columnIndex,columnWidth * 500);}}}}private Integer dataLength (List<CellData> cellDataList,Cell cell,Boolean isHead) {if (isHead) {int bytesLength = cell.getStringCellValue().getBytes().length;if (bytesLength < 10) {return bytesLength;} else {int stringLength = cell.getStringCellValue().length();Double v = (bytesLength + stringLength) * 0.5;return v.intValue();}} else {CellData cellData = cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch (type) {case STRING:int bytesLength = cellData.getStringValue().getBytes().length;if (bytesLength < 10) {return bytesLength;} else {int stringLength = cellData.getStringValue().length();Double v = (bytesLength + stringLength) * 0.3;return v.intValue();}case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}
}
util
private List<Map<String, Object>>getDataList(Map<String, String> params) {List<Map<String, Object>> reuslt = new ArrayList<>();Map<String, Object> map = new HashMap<>();map.put("dw","测试单位");map.put("y","10");map.put("w","800");map.put("sj","2023-07-01 12:12:00");reuslt.add(map);return reuslt;
}private List<List<String>>getData(List<Map<String, Object>> dataList) {List<List<String>> result = new ArrayList<>();for (Map<String, Object> map : dataList) {List<String> list = new ArrayList<>();list.add(map.get("dw").toString());list.add(map.get("y").toString());list.add(map.get("w").toString());list.add(map.get("sj").toString());result.add(list);}return result;
}
前端代码
exportXlsx () {this.$axios({method: 'post',url: '/test/exportDemo',responseType: 'blob',data: {...this.params}}).then(response => {let filename = response.headers['content-disposition']const blob = new Blob([response.data])var downloadElement = document.createElement('a')var href = window.URL.createObjectURL(blob)downloadElement.href = hrefdownloadElement.download = decodeURIComponent(filename.split('filename=')[1])document.body.appendChild(downloadElement)downloadElement.click()document.body.removeChild(downloadElement)window.URL.revokeObjectURL(href)}).catch(reject => {})
}
若依
配置多数据源
若依配置多数据源,分别为不同数据库时示例