Introduction

js前端生成excel文件(表格)并下载后台返回一段数据,前端遍历生成表格下载

Use

  1. function downLoadExcel(data, fileName) {
  2. //定义表头
  3. let str = `77\n用户名,时间,坐标,来源,授权时间\n`;
  4. //增加\t为了不让表格显示科学计数法或者其他格式
  5. for (let i = 0; i < data.length; i++) {
  6. for (let item in data[i]) {
  7. str += `${data[i][item] + '\t'},`;
  8. }
  9. str += '\n';
  10. }
  11. //encodeURIComponent解决中文乱码
  12. let uri = 'data:text/xlsx;charset=utf-8,\ufeff' + encodeURIComponent(str);
  13. //通过创建a标签实现
  14. let link = document.createElement('a');
  15. link.href = uri;
  16. //对下载的文件命名
  17. link.download = `${fileName || '表格数据'}.csv`;
  18. document.body.appendChild(link);
  19. link.click();
  20. document.body.removeChild(link);
  21. }
  22. function clickDown() {
  23. let tableData = [
  24. {
  25. name: '你好啊',
  26. time: 130000000000,
  27. pre: '127.130',
  28. source: '淘宝',
  29. otherTime: 1571276232000,
  30. },
  31. {
  32. name: '2你好啊',
  33. time: 5130000000000,
  34. pre: '127.130',
  35. source: '淘宝',
  36. otherTime: 41571276232000,
  37. },
  38. {
  39. name: '3你好啊',
  40. time: 3130000000000,
  41. pre: '127.130',
  42. source: '淘宝',
  43. otherTime: 21571276232000,
  44. },
  45. ];
  46. downLoadExcel(tableData, '测试数据');
  47. }

Example

image.png
原文链接:https://blog.csdn.net/guoqiankunmiss/article/details/102609250