1.后端导入maven
org.apache.poi
poi
3.15-beta2
org.apache.poi
poi-ooxml
3.15-beta2
commons-collections
commons-collections
3.2.2
2.导出表格工具类
package com.dawei.cardsolution.modules.card.utils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.commons.collections.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
public class FilePortUtil {
public static void exportExcel(HttpServletResponse response, String title, String[] headers, List list, List containBean) throws Exception{
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
HSSFRow row = sheet.createRow(0);
//创建第一行表头
for (short i = 0; i < headers.length; i++){
HSSFCell cell = row.createCell(i);
HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
cell.setCellValue(textString);
}
Iterator it = list.iterator();
int index = 0;
while (it.hasNext()){
index++;
row = sheet.createRow(index);
T t = (T)it.next();
//通过反射得到字段
Field[] fields = t.getClass().getDeclaredFields();
//如果需要匹配
if (CollectionUtils.isEmpty(containBean)){
for (int j = 0; j < containBean.size(); j++){
for (int i = 0; i < fields.length; i++){
Field field = fields[i];
if (!field.getName().equals(containBean.get(j)))
continue;
setCellValue(t,field,row,j);
}
}
} else {
for (int i = 0; i < fields.length; i++){
Field field = fields[i];
setCellValue(t,field,row,i);
}
}
}
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + new String((title).getBytes(), "ISO8859-1") + ".xls");
workbook.write(response.getOutputStream());
}finally {
if (workbook != null){
workbook.close();
}
}
}
private static void setCellValue(T t, Field field, HSSFRow row, int index) {
HSSFCell cell = row.createCell(index);
Object value = invoke(t, field);
String textValue = null;
if (value != null){
if (value instanceof Date){
Date date = (Date) value;
textValue = DateFormatUtils.format(date,"yyyy-MM-dd HH:mm:ss");
} else {
textValue = value.toString();
}
}
if (textValue != null){
cell.setCellValue(textValue);
}
}
private static Object invoke(T t, Field field){
try{
String fieldName = field.getName();
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName,t.getClass());
Method readMethod = propertyDescriptor.getReadMethod();
return readMethod.invoke(t);
}catch (Exception e){
return null;
}
}
}
3.controller层
@ResponseBody
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response){
//导出的表格名称
String title = "消费";
//表中第一行表头字段
String [] headers ={"序号","姓名","部门","卡号","消费金额","账户余额","消费类型","消费方式","是否当天第一次消费","消费时间","消费单号"};
//从数据库查询出来的结果集
List canteenConsumptionRecordExcels = canteenConsumptionRecordDao.selectCanteenConsumptionRecords();
//具体需要写入excel需要的那些字段,这些字段从PprojectSalary类中拿,也就是上面的实际数据结果集的泛型
List list = Arrays.asList("id","name","department","idCard","balance","money","consumeTypeName","typeName","isFirstName","date","cid");
System.out.println(list);
System.out.println(response);
try {
FilePortUtil.exportExcel(response,title,headers,canteenConsumptionRecordExcels,list);
}catch (Exception e){
e.printStackTrace();
}
}
4.前端接口调用 注:如果用的框架则不能使用封装的axios发请求否则会导致UTF-8失效而乱码!
导出 //导出 按钮 exportOut() { axios({ // 用axios发送get请求 method: 'get', url: window.SITE_CONFIG.baseUrl+'/card/canteenconsumptionrecord/exportExcels', //请求地址 responseType: 'blob', // 表明返回服务器返回的数据类型 headers: { token:Vue.cookie.get('token'), 'Content-Type': 'application/json' } }).then(res => { // 处理返回的文件流 //new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层) const blob = new Blob([res.data],{type: "application/vnd.ms-excel"}); const fileName = '消费.xlsx';//下载文件名称 const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); }) //js方法 },



