接到一个需求 ,是有关Excel导出的功能,用户通过页面的数据,进行批量的导出操作。话不多说,直接上代码:
后端
package com.ly.travelaround.cms.common.utils;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ExportEntityToExcel {
private static final Logger logger = LoggerFactory.getLogger(ExportEntityToExcel.class);
public static <T> void export(String excelName, List<T> list, LinkedHashMap<String, String> fieldMap, HttpServletResponse response, HttpServletRequest request) {
if (excelName == null || excelName == "") {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String defaultName = sdf.format(new Date());
excelName = defaultName;
}
try {
String fileName = new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls";
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
} catch (Exception e1) {
logger.info(e1.getMessage());
}
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(excelName);
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
fillSheet(sheet, list, fieldMap, style);
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
logger.info("导出Excel失败!");
logger.error(e.getMessage());
}
}
public static Field getFieldByName(String fieldName, Class<?> clazz) {
Field[] selfFields = clazz.getDeclaredFields();
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
return null;
}
public static Object getFieldValueByName(String fieldName, Object o) throws Exception {
Object value = null;
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
value = field.get(o);
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名: " + fieldName);
}
return value;
}
public static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
Object value = null;
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
Object fieldObj = getFieldValueByName(attributes[0], o);
String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
public static <T> void fillSheet(HSSFSheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap, HSSFCellStyle style) throws Exception {
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
HSSFRow row = sheet.createRow((int) 0);
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 3000);
}
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
row.setRowStyle(style);
row.createCell(i).setCellValue(fieldValue);
}
}
}
}
@RestController("excel")
public class ExcelExportController {
@PostMapping(value = "downLoadExcel")
public void downLoadExcel(HttpServletResponse response, HttpServletRequest request, @RequestBody() List<ExcelPo> dataList) {
if (null == dataList || dataList.size() <= 0) {
return ;
}
response.setCharacterEncoding("utf-8");
String excelName = "酒店列表";
LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
fieldMap.put("order", "排序值");
fieldMap.put("cityId", "城市ID");
fieldMap.put("hotelId", "商品ID");
fieldMap.put("hotelName", "商品名称");
fieldMap.put("start", "星级");
fieldMap.put("score", "评分");
fieldMap.put("commentTotal", "点评数量");
fieldMap.put("price", "价格");
fieldMap.put("filterName", "商圈名称");
new ExportEntityToExcel().export(excelName, dataList, fieldMap, response, request);
}
}
其中后端代码是使用的—参考链接—的代码。
前端
<el-button :disabled="isActive" @click="exportChoosed" type="info"
>导出数据</el-button>
exportChoosed() {
const link = document.createElement("a");
console.log("chooosedList", choosedList);
hotelList
.exportChoosedToExcel(choosedList)
.then((res) => {
let blob = new Blob([res], { type: "application/vnd.ms-excel" });
let objectUrl = URL.createObjectURL(blob);
debugger;
link.href = objectUrl;
link.download = "酒店列表";
link.click();
window.URL.revokeObjectURL(objectUrl);
})
.catch((err) => {
console.log("被catch到了", err);
return {
code: 500,
success: false,
msg: err,
};
});
}