java: springboot+elementui导出功能模板

java: springboot+elementui导出功能模板

前端代码:

1.js公共方法

 /**
   * 导出Excel调用公共方法
   * @param url 导出Excel的业务接口地址
   * @param ids 需要导出的业务id集合
   */
  exportExcel: function (url,ids) {
    var form = document.createElement('form')
    form.style.display = 'none'
    form.action =项目路径+url;
    form.method='post'
    document.body.appendChild(form)
    //动态创建input并给value赋值
    var input= document.createElement('input');
    input.type='hidden';
   input.name='ids';
    input.value=ids;
    form.appendChild(input);
    form.submit()
   form.remove()

  },

2.调用

<script>
	import commonJs from "@/pages/opinion/utils/common.js"
	
      //方法
  methods: {
        exportTestPoint: function () {
            let _this = this;
            let message = "确定导出所选数据?";
            if (_this.selectIds.length == 0) {
                return this.$message.warning("请选择需要导出的数据!");
            }
            //提示框
            this.$confirm(message, "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "关闭",
                type: "warning",
            }).then(() => {
                //列表所选的id
                let ids = _this.selectIds.join(",");
                commonJs.exportExcel("/api/testPoint/export", ids);
            });
        },
  }
</script>

后端代码

0.导出工具类

/**
 * @description: 导出Excel工具类
 * @author:YangYj
 * @Date: 2021/9/18 14:35
 */
public class ExportExcelUtil {
    /**
     * 导出Excel
     * @param fileName 文件名称
     * @param titles 导出文件的标题
     * @param dataList 需要导出的数据集合
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> export(String fileName, String[] titles, List<Map<String, Object>> dataList) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();//创建一个Excel文件
        //创建Excel文档属性,必不可少。少了的话,getDocumentSummaryInformation()方法就会返回null
        workbook.createInformationProperties();
        DocumentSummaryInformation info = workbook.getDocumentSummaryInformation();
        info.setCategory(fileName);//设置文件名

        //设置文件中的日期格式
        HSSFCellStyle datecellStyle = workbook.createCellStyle();
        datecellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));//这个文件的日期格式和平时的不一样

        //创建表单
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow r0 = sheet.createRow(0);//创建第一行
        int columnNum = titles.length;
        //===================创建标题行=============//
        HSSFCellStyle headStyle = getHeaderStyle(workbook);
        for (int i = 0; i < columnNum; i++) {
            HSSFCell cell = r0.createCell(i);// 创建列
            cell.setCellValue(titles[i]);
            cell.setCellStyle(headStyle);//设置标题行样式
        }
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> map = dataList.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            for (int j = 0; j < columnNum; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(map.get(titles[j]) == null ? "" : map.get(titles[j]).toString());
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",
                new String((fileName+".xls").getBytes("UTF-8"), "iso-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        ResponseEntity<byte[]> entity = new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.CREATED);
        baos.close();
        return entity;
    }

    /**
     * 表格标题样式
     */
    private static HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 设置字体颜色
        font.setColor(IndexedColors.AUTOMATIC.getIndex());
        // 字体加粗
        font.setBold(true);
        // 设置字体名字
        font.setFontName("黑体");
        // 设置样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置标题背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
//        // 设置背景颜色填充样式
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        // 设置低边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置低边框颜色
        style.setBottomBorderColor(IndexedColors.AUTOMATIC.getIndex());
        // 设置右边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框
        style.setTopBorderColor(IndexedColors.AUTOMATIC.getIndex());
        // 设置顶边框颜色
        style.setTopBorderColor(IndexedColors.AUTOMATIC.getIndex());
        // 在样式中应用设置的字体
        style.setFont(font);
        // 设置自动换行
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
        return style;
    }

}

1.controller

/**
     * 导出excel
     * ResponseEntity里面装了所有响应的数据
     */
    @PostMapping("/export")
    @ResponseBody
    public ResponseEntity<byte[]> exportExcel(HttpServletResponse response, @RequestParam String ids) throws IOException {
        String[] idsArray = ids.split(",");
        List<String> idList = Arrays.asList(idsArray);
        //数据的查询方法
        List<TestPointBase> dataList = this.service.findAllByIds(idList);
       
        String title[] = {"编号", "名称", "专业代号", "专业名称", "动作代号", "动作名称", "试验目的","试验方法"};
        return ExportExcelUtil.export("表名", title, this.findExportDataMapFromList(dataList));
    }


 /**
     * 将查询出的要导出为excel的数据进行封装,方便进行excel导出
     */
    public List<Map<String, Object>> findExportDataMapFromList(List<TestPointBase> parametersList) {
        List<Map<String, Object>> exportList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != parametersList && parametersList.size() > 0) {
            for (TestPointBase data : parametersList) {
                Map<String, Object> map = new HashedMap();
 String title[] = {"", "", "", "", "", "", "", "", "","", "",""};
    
                map.put("编号", data.getNumber());
                map.put("名称", data.getName());
                map.put("专业代号", data.getFirstSpecialtyNumber());
                map.put("专业名称", data.getFirstSpecialtyName());
              
                map.put("动作代号", data.getActionNumber());
                map.put("动作名称", data.getActionName());
                map.put("试验目的", data.getPurpose());
       
                map.put("试验方法", data.getResult());
                exportList.add(map);
            }
        }
        return exportList;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值