JavaScript 把数据存储到Excel

时间:2024-03-05 15:54:07

工作中,导出数据到表格的功能很多吧,

以下是我  导出数据到Excel表格  的方法:

一 .首先需要引用JS脚本:   直接复制全部脚本, 写到一个js文件里面,引用就行了

  1 /* eslint-disable */
  2 let idTmr;
  3 const getExplorer = () => {
  4     let explorer = window.navigator.userAgent;
  5     //ie
  6     if (explorer.indexOf("MSIE") >= 0) {
  7         return \'ie\';
  8     }
  9     //firefox
 10 
 11     else if (explorer.indexOf("Firefox") >= 0) {
 12         return \'Firefox\';
 13     }
 14     //Chrome
 15     else if (explorer.indexOf("Chrome") >= 0) {
 16         return \'Chrome\';
 17     }
 18     //Opera
 19     else if (explorer.indexOf("Opera") >= 0) {
 20         return \'Opera\';
 21     }
 22     //Safari
 23     else if (explorer.indexOf("Safari") >= 0) {
 24         return \'Safari\';
 25     }
 26 }
 27 // 判断浏览器是否为IE
 28 const exportToExcel = (data, name) => {
 29 
 30     // 判断是否为IE
 31     if (getExplorer() == \'ie\') {
 32         tableToIE(data, name)
 33     } else {
 34         tableToNotIE(data, name)
 35     }
 36 }
 37 
 38 const Cleanup = () => {
 39     window.clearInterval(idTmr);
 40 }
 41 
 42 // ie浏览器下执行
 43 const tableToIE = (data, name) => {
 44     let curTbl = data;
 45     let oXL = new ActiveXObject("Excel.Application");
 46 
 47     //创建AX对象excel
 48     let oWB = oXL.Workbooks.Add();
 49     //获取workbook对象
 50     let xlsheet = oWB.Worksheets(1);
 51     //激活当前sheet
 52     let sel = document.body.createTextRange();
 53     sel.moveToElementText(curTbl);
 54     //把表格中的内容移到TextRange中
 55     sel.select;
 56     //全选TextRange中内容
 57     sel.execCommand("Copy");
 58     //复制TextRange中内容
 59     xlsheet.Paste();
 60     //粘贴到活动的EXCEL中
 61 
 62     oXL.Visible = true;
 63     //设置excel可见属性
 64 
 65     try {
 66         let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
 67     } catch (e) {
 68         print("Nested catch caught " + e);
 69     } finally {
 70         oWB.SaveAs(fname);
 71 
 72         oWB.Close(savechanges = false);
 73         //xls.visible = false;
 74         oXL.Quit();
 75         oXL = null;
 76         // 结束excel进程,退出完成
 77         window.setInterval("Cleanup();", 1);
 78         idTmr = window.setInterval("Cleanup();", 1);
 79     }
 80 }
 81 
 82 // 非ie浏览器下执行
 83 const tableToNotIE = (function () {
 84     // 编码要用utf-8不然默认gbk会出现中文乱码
 85     let uri = \'data:application/vnd.ms-excel;base64,\',
 86         template = \'<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"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>\',
 87         base64 = function (s) {
 88             return window.btoa(unescape(encodeURIComponent(s)));
 89 
 90         },
 91 
 92         format = (s, c) => {
 93             return s.replace(/{(\w+)}/g,
 94                 (m, p) => {
 95                     return c[p];
 96                 })
 97         }
 98     return (table, name) => {
 99         let ctx = {
100             worksheet: name,
101             table
102         }
103 
104         //创建下载
105         let link = document.createElement(\'a\');
106         link.setAttribute(\'href\', uri + base64(format(template, ctx)));
107 
108         link.setAttribute(\'download\', name);
109 
110 
111         // window.location.href = uri + base64(format(template, ctx))
112         link.click();
113     }
114 })()
115 
116 // 导出函数
117 const export2Excel = (theadData, tbodyData, dataname) => {
118 
119     let re = /http/ // 字符串中包含http,则默认为图片地址
120     let th_len = theadData.length // 表头的长度
121     let tb_len = tbodyData.length // 记录条数
122     let width = 200// 设置图片大小
123     let height = 100
124 
125     // 添加表头信息
126     let thead = \'<thead><tr>\'
127     for (let i = 0; i < th_len; i++) {
128         thead += \'<th>\' + theadData[i] + \'</th>\'
129     }
130     thead += \'</tr></thead>\'
131 
132     // 添加每一行数据
133     let tbody = \'<tbody>\'
134     for (let i = 0; i < tb_len; i++) {
135         tbody += \'<tr>\'
136         let row = tbodyData[i] // 获取每一行数据
137 
138         //有图片的话  ,就把下面的if打开
139         for (let key in row) {
140             //if (re.test(row[key])) { // 如果为图片,则需要加div包住图片
141             //    // 
142             //    tbody += \'<td style="width:\' + width + \'px; height:\' + height + \'px; text-align: center; vertical-align: middle"><div style="display:inline"><img src=\\'\' + row[key] + \'\\' \' + \' \' + \'width=\' + \'\"\' + width + \'\"\' + \' \' + \'height=\' + \'\"\' + height + \'\"\' + \'></div></td>\'
143             //} else {
144                 tbody += \'<td style="text-align:center">\' + row[key] + \'</td>\'
145             //}
146         }
147 
148         tbody += \'</tr>\'
149     }
150     tbody += \'</tbody>\'
151 
152     let table = thead + tbody
153 
154     // 导出表格
155     exportToExcel(table, "C:\Users\Mloong\Desktop")
156 }
JS脚本包

 

二 . js代码:  post请求一个ExproExcel的方法,返回的是要导出的数据。

     ret返回的数据格式为 数组的对象, tHeader是Excel表格的头部,

 1   $.post(\'ExprotExcel\', null, function (ret) {
 2 
 3         let tHeader = [
 4             \'申请编号\',
 5             \'体现人\',
 6             \'缴税金额\',
 7             \'金额\',
 8             \'总金额\',
 9             \'审核状态\',
10             \'提现方式\',
11             \'创建时间\',
12         ]
13         let tbody = ret;  //Excel表数据,json返回,为数组对象的结构
14         export2Excel(tHeader, tbody);
15     });
JS代码

 

  PS: ret 返回的格式是这样的:

 1 let tbody = [
 2         {
 3             name: \'玫瑰花\',
 4             color: \'红色\',
 5             pic: \'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2801998497,4036145562&fm=27&gp=0.jpg\'
 6         },
 7         {
 8             name: \'菊花\',
 9             color: \'黄色\',
10             pic: \'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1506844670,1837003941&fm=200&gp=0.jpg\'
11         },
12         {
13             name: \'牵牛花\',
14             color: \'紫色\',
15             pic: \'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3056120770,1115785765&fm=27&gp=0.jpg\'
16         },
17         {
18             name: \'梅花\',
19             color: \'白色\',
20             pic: \'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2700343322,3431874915&fm=27&gp=0.jpg\'
21         },
22         {
23             name: \'桃花花\',
24             color: \'粉色\',
25             pic: \'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=602076004,4209938077&fm=27&gp=0.jpg\'
26         }
27     ]
28 --------------------- 
29 作者:little小 
30 来源:CSDN 
31 原文:https://blog.csdn.net/xiaoxiaojie12321/article/details/81780900 
32 版权声明:本文为博主原创文章,转载请附上博文链接!
View Code

 

三: 这种格式的数据  ,那么我就可以直接到后台返回了:

  就是 List集合类型的对象 ,ToArray 一下就行了

 1 public ActionResult ExprotExcel()
 2         {
 3             var lists = (from a in es_EGDSuperRecordService.Instance.LoadEntities()
 4                          join b in es_AgentsService.Instance.LoadEntities() on a.sendid equals b.AgentsID
 5                          orderby a.createtime descending
 6                          select new
 7                          {
 8 
 9                              id = a.id,
10                              AgentsName = b.AgentsName,
11                              feenumber = a.feenumber,
12                              number = a.number,
13                              allnumber = a.allnumber,
14                              flag = a.flag == 0 ? "待审核" : a.flag==1?"审核通过":"审核不通过",
15                              sendaddress = a.sendaddress,
16                              createtime = a.createtime,
17                          }).ToList();
18 
19             return Json(lists.ToArray(),JsonRequestBehavior.AllowGet);
20         }
View Code

 

 

脚本包里面的  一些东西,看得懂 是可以直接改的。