微信小程序:json生成excel

我是写到util里然后调用该方法

//json数据转excel——util.js
function JSONToExcelConvertor(JSONData, FileName) {
  var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
  var excel = '<table>';
//设置表头
var head = "<td>名字</td><td>年龄</td><td>地点</td>"; //因为第一行tr包裹会导致下面多出来一行,所以不加tr包裹
excel  += head;
//此处写循环 拼html 表内容部分
for(var i=0;i<JSONData.length;i++){
excel += "<tr>";
excel += "<td>"+JSONData[i].name"</td>";
excel += "<td>"+JSONData[i].age"</td>";
excel += "<td>"+JSONData[i].area"</td>";
excel += "</tr>";
}
  excel += "</table>";
  var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
  excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
  excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
  excelFile += '; charset=UTF-8">';
  excelFile += "<head>";
  excelFile += "<!--[if gte mso 9]>";
  excelFile += "<xml>";
  excelFile += "<x:ExcelWorkbook>";
  excelFile += "<x:ExcelWorksheets>";
  excelFile += "<x:ExcelWorksheet>";
  excelFile += "<x:Name>";
  excelFile += FileName; //标签名
  excelFile += "</x:Name>";
  excelFile += "<x:WorksheetOptions>";
  excelFile += "<x:DisplayGridlines/>";
  excelFile += "</x:WorksheetOptions>";
  excelFile += "</x:ExcelWorksheet>";
  excelFile += "</x:ExcelWorksheets>";
  excelFile += "</x:ExcelWorkbook>";
  excelFile += "</xml>";
  excelFile += "<![endif]-->";
  excelFile += "</head>";
  excelFile += "<body>";
  excelFile += excel;
  excelFile += "</body>";
  excelFile += "</html>";
  var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);
  return uri;

module.exports = {
  JSONToExcelConvertor
}

//需要引用的页面 js部分

const util = require('../../utils/util.js')
//取到json(json),标签名 (filename)
var excelUrl =util(json,filename);
//无法通过wx.downloadFile直接下载,因为excelUrl 过长,目前我用的wx.setClipboardData复制链接 然后自己通过手机上的浏览器下载。

实际上还是有三个问题没有解决,最近太忙了,等有时间再回来研究。
1.就是首行用tr包裹会有空格
2.下载的文件名没有自定义,使用的默认的。
3.链接过长。
最好的方法其实还是让后台提供个下载链接,因为客户要求不高就直接在前端用js解决了,有更好解决方案的朋友可以在下面评论或者私信告诉我下,谢谢大家!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容