vue通用导出组件的实现导出 excel csv pdf

后台管理项目中经常使用文件导入导出,故封装了一个通用导出组件的实现

2636012-77dd7ded77e819a2.jpg
通用导出

思路 使用 Dropdown 控件选择导出类型 触发导出
导出的table 数据类型

tableColumns: [
      {
        title: '序号',
        key: 'Ordinal',
        align: 'center'
      },
      {
        title: '产品编号',
        key: 'ProductNo',
        align: 'left'
      }
]
tableData: [{Ordinal:1,ProductNo:'1234',ProductDesc:'1232222'}]

导出文件大部分情况下是后端处理,有时候我们只需要js处理 该怎么做呢?

1.导出CSV

首先实现导出CSV格式
拼接 csv格式其实就是个纯文本文件,中间使用逗号或者换行符进行拼接
这里使用 json2cvs这个包 需要npm 安装 npm install json2csv -s
下载方式
对于微软系浏览器(IE和Edge)和非微软系列浏览器采用两种不同的方式进行下载
IE和Edge 采用了 navigator.msSaveBlob 方法 此方法为IE10及以上特有,IE10以下勿采用
非微软浏览器 使用a标签的click事件进行下载
关键代码

try {
      const result = json2csv.parse(rows, {
        fields: fields,
        excelStrings: true
      });
      if (this.MyBrowserIsIE()) {
        // IE10以及Edge浏览器
        var BOM = "\uFEFF";
         // 文件转Blob格式
        var csvData = new Blob([BOM + result], { type: "text/csv" });
        navigator.msSaveBlob(csvData, `${fileName}.csv`);
      } else {
        let csvContent = "data:text/csv;charset=utf-8,\uFEFF" + result;
        // 非ie 浏览器
        this.createDownLoadClick(csvContent, `${fileName}.csv`);
      }
    } catch (err) {
      alert(err);
    }
  //创建a标签下载
  createDownLoadClick(content, fileName) {
    const link = document.createElement("a");
    link.href = encodeURI(content);
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  },
  // 判断是否IE浏览器
  MyBrowserIsIE() {
    let isIE = false;
    if (
      navigator.userAgent.indexOf("compatible") > -1 &&
      navigator.userAgent.indexOf("MSIE") > -1
    ) {
      // ie浏览器
      isIE = true;
    }
    if (navigator.userAgent.indexOf("Trident") > -1) {
      // edge 浏览器
      isIE = true;
    }
    return isIE;
  },
2.导出Excel类型文件

导出excel借鉴了iview-admin 自带的excel操作js(需要npm安装 xlsx)npm install xlsx -s
需要导出的地方调用excel.export_array_to_excel函数即可

const param = {
title: titles,
key: keys,
data: this.exportData,
autoWidth: true,
filename: this.exportFileName
};
excel.export_array_to_excel(param);

完整excel操作js代码如果 excel.js
参考博文

https://www.cnblogs.com/muyangw/p/10306152.html

3.导出pdf

最开始使用jspdf 包 把 需要导出的table使用 canvas生成图片,然后把图片插入pdf内,但是这种方式不容易控制,并且生成的pdf清晰度不高,如果直接写pdf又会产生对中文支持的不友好,后采用前后端配合生成pdf文件并导出

使用blob的方式 后端返回文件流前端 接收并下载
主要代码如下

//思路 webapi返回二进制的文件流 js 通过Blob接收并转换成pdf文件下载
this.$axios({
method: "post",
Prefix: "",
data: {
ExCode: "IRAP_RPT_DownLoadFile",
fileName: this.exportFileName,
access_token: this.$cookies.get("access_token"),
valueKeys: valueKeys, //"Product,Version,Description",
labeNames: labeNames, // "产品,版本,描述",
tableData: tableData
}
// responseType:'blob'
})
.then(response => {
// base64字符串转 byte[]
var bstr = atob(response.data.FileInfo),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 转blob
var blob = new Blob([u8arr], {
type: `application/pdf;charset-UTF-8`
})
if (this.MyBrowserIsIE()) {
// IE10以及Edge浏览器
var BOM = "\uFEFF";
// 传入 Blob 对象
navigator.msSaveBlob(blob, `${this.exportFileName}.pdf`);
} else {
// 非ie 浏览器
let content = window.URL.createObjectURL(blob);
this.createDownLoadClick(content, `${this.exportFileName}.pdf`);
}
})
.catch(err => {
console.log(err);
});

因为公司接口通用规范我这里返回的是文件的base64字符串

如果后台直接返回了二进制的文件流 就不用再次进行转换 并且需要加上responseType:'blob'这句

后台接口采用C# webapi 的方式主要代码如下

  public string DownLoadFile(string clientID, string msgFormat, string inParam)

  {

      dynamic res = new System.Dynamic.ExpandoObject();

      try

      {

          dynamic dn = inParam.GetSimpleObjectFromJson();

          string token = dn.access_token.ToString();

          // 解析Json 字符串中的数组然后 转实体对象

          string fileName = dn.fileName;

          string lbelObj = dn.labeNames;

          string valueKeyObj = dn.valueKeys;

          object[] tableObj = dn.tableData;

          string tableJson = JsonConvert.SerializeObject(tableObj);

          string[] valueKeys = valueKeyObj.Split(',');

          string[] labeNames = lbelObj.Split(',');

          //string[] valueKeys = new string[] { "Product", "Version",  "Description" }; ;

          //string[] labeNames = new string[] { "产品", "版本", "描述" }; ;

          DataTable tblDatas = new DataTable("Datas");

          //string jsonStr =  "[{\"Product\":\"1\",\"Version\":\"1\",\"Description\":\"1\"}]";

          tblDatas = ToDataTableTwo(tableJson);

          PDFHelper pdfHelper = new PDFHelper();

          byte[] array = pdfHelper.ExportPDF(fileName, labeNames, tblDatas,  valueKeys);

          // 文件byte数组转base64字符串

          string str = Convert.ToBase64String(array);;

          byte[] bt = array.ToArray();

          res.ErrCode = 0;

          res.ErrText = "文件生成成功";

          res.FileInfo = str;

          return JsonConvert.SerializeObject(res);

      }

      catch (Exception ex)

      {

          //throw new Exception(ex.Message);

          res.ErrCode = 9999;

          res.ErrText = "Excel导入异常:" + ex.Message;

          return JsonConvert.SerializeObject(res);

      }

  }

C# pdf生成 使用itextsharp

父组件调用代码

<MyExportType :exportFileName='`test`' v-on:myHandleRepeatExprot="myRepeatExprot"
          :isPagination="isPagination" :exportData="exportData" :exportColumns="exportColumns" ref="MyExportType"></MyExportType>

如果父组件分页的需要导出所有未分页的数据 需要再次调用查询table数据的接口并且给exportData赋值

  async myRepeatExprot(name) {
      // 查询所有
      await this.geBTtResult(1)

      // 调用子组件的导出事件

      await this.$refs.MyExportType.exportFile(name)

    },

否则 未分页或者导出当前页 直接导出即可 不需要通过父组件调用子组件事件

猜你喜欢

转载自blog.csdn.net/weixin_34268843/article/details/87130075