基于Controller与axios以post实现的数据导出功能

注:内容有参考,但是找不到具体的文章,如有发现,请及时联系

ExportExcel工具类的定义

pom.xml文件导入对应包

 <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
 </dependency>

java中新建ExportExcelUtil 类

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
public final class ExportExcelUtil {
	//工作簿
    private static HSSFWorkbook workbook;
    // 工作表
    private static HSSFSheet sheet;
    // 标题行开始位置
    private static final int TITLE_START_POSITION = 0;
    // 时间行开始位置
    private static final int DATEHEAD_START_POSITION = 1;
    // 表头行开始位置
    private static final int HEAD_START_POSITION = 2;
    //文本行开始位置
    private static final int CONTENT_START_POSITION = 3;
    
	//初始化
    public static HSSFWorkbook excelExport(List<?> dataList, Map<String, String> titleMap, String sheetName) {
        initHSSFWorkbook(sheetName);
        createTitleRow(titleMap, sheetName);
        createDateHeadRow(titleMap);
        createHeadRow(titleMap);
        createContentRow(dataList, titleMap);
        return workbook;
    }

    private static void initHSSFWorkbook(String sheetName) {
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
    }

   // 生成标题(第零行创建)
    private static void createTitleRow(Map<String, String> titleMap, String sheetName) {
        CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);
        sheet.addMergedRegion(titleRange);
        HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(sheetName);
    }

    // 创建时间行(第一行创建)
    private static void createDateHeadRow(Map<String, String> titleMap) {
        CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);
        sheet.addMergedRegion(dateRange);
        HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
        HSSFCell dateCell = dateRow.createCell(0);
        dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
    }

    // 创建表头行(第二行创建)
    private static void createHeadRow(Map<String, String> titleMap) {
        // 第1行创建
        HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);
        int i = 0;
        for (String entry : titleMap.keySet()) {
            HSSFCell headCell = headRow.createCell(i);
            headCell.setCellValue(titleMap.get(entry));
            i++;
        }
    }

    private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {
        try {
            int i=0;
            for (Object obj : dataList) {

                HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);
                int j = 0;
                for (String entry : titleMap.keySet()) {
                    String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);
                    Method m = obj.getClass().getMethod(method, null);
                    String value="";
                    if (m.invoke(obj, null)!=null)//不为null写入数据
                         value =   m.invoke(obj, null).toString();
                    HSSFCell textcell = textRow.createCell(j);
                    textcell.setCellValue(value);
                    j++;
                }
                i++;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

新建Controller类

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orders.pojo.Result;
import com.orders.utils.ExportExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

@RestController
@CrossOrigin //跨域
public class DownloadResultController {

    @RequestMapping(value = "/downloadAllUserResult/result", method = RequestMethod.POST)
    public void downloadAllUserResult(HttpServletRequest req, HttpServletResponse res) throws Exception {
		// 设置编码格式防止乱码
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        UUID uuid = UUID.randomUUID();
        String filedisplay = uuid + ".xls";
        
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String List = jsonObject.getString("resultList");

        List<Result> list2 = JSONArray.parseArray(List, Result.class);

        List<Result> list3 = new ArrayList<>();
        for (Result r : list2) {
            if (r.getId() != null) {
                list3.add(r);
            }
        }
        Map<String, String> titleMap = new LinkedHashMap<String, String>();
        titleMap.put("id", "id");
        titleMap.put("userUsername", "手机号");
        titleMap.put("userName", "姓名");
        titleMap.put("userSex", "性别");
        titleMap.put("position", "地址");
        titleMap.put("orderTime", "时间");
        titleMap.put("timeDuan", "时间段");
        titleMap.put("userNum", "序号");
        titleMap.put("orderState", "状态");
        res.setHeader("Access-Control-Expose-Headers","content-disposition");//不写前端无法获取content-disposition
        res.setContentType(req.getServletContext().getMimeType(filedisplay));
        res.setHeader("content-disposition","attachment;filename="+filedisplay);
        HSSFWorkbook sheets = ExportExcelUtil.excelExport(list3, titleMap, sheetName);
        ServletOutputStream outputStream = res.getOutputStream();
        sheets.write(outputStream);
        outputStream.close();
    }
}

前端js部分

download() {
	axios({
		method:'post',
		url:'/downloadAllUserResult/result',
		data: {
			resultList: this.resultList// 前端已有的数据list
		},
		responseType:'blob' //解决前端导出xls文件乱码问题
	}).then(res=>{
		let contentType=res.headers['content-type'];//从response的headers获取contentType
		const blob = new Blob([res.data], {type: contentType});
		const downloadElement = document.createElement('a');
		const href = window.URL.createObjectURL(blob);
		let contentDisposition = res.headers["content-disposition"];  //从response的headers中获取content-disposition
		let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
		let result = patt.exec(contentDisposition);
		let filename = decodeURI(result[1]);
		downloadElement.style.display = 'none';
		downloadElement.href = href;
		downloadElement.download = filename ; //下载后文件名
		document.body.appendChild(downloadElement);
		downloadElement.click(); //点击下载
		document.body.removeChild(downloadElement); //下载完成移除元素
		window.URL.revokeObjectURL(href); //释放掉blob对象
	}).catch(function(error) {
		console.log(error);
	});
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeFondOfSunday

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值