简介

读取,操作并写入电子表格数据和样式到 XLSX 和 JSON 文件。 一个 Excel 电子表格文件逆向工程项目。 注意:excelJS 没有实现 Brower 端操作文件,如果要解析 **.xlsx 文件只能在 node 端

安装或引入

  1. // ExcelJS 在 dist/ 文件夹内发布了两个支持浏览器的包:
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
  3. <script src="exceljs.js"></script>
  4. // 使用 npm:
  5. npm install exceljs
  1. import * as XLSX from 'xlsx';

json转excel文件

  1. async function jsonToExcel() {
  2. /* 创建一个工作薄 */
  3. const workbook = new window.ExcelJS.Workbook();
  4. /* 创建sheet对象 */
  5. const sheet = workbook.addWorksheet('表一');
  6. /* 添加表头 */
  7. sheet.columns = [
  8. {
  9. header: '工号',
  10. key: 'id',
  11. width: 15,
  12. // style: {
  13. // font: { name: 'Arial', size: 12 },
  14. // border: {
  15. // top: { style: 'thin' },
  16. // left: { style: 'thin' },
  17. // bottom: { style: 'thin' },
  18. // right: { style: 'thin' },
  19. // },
  20. // alignment: {
  21. // vertical: 'middle',
  22. // horizontal: 'center',
  23. // },
  24. // },
  25. },
  26. { header: '姓名', key: 'name', width: 15 },
  27. ];
  28. /* 需要添加的数据 */
  29. const data = [
  30. {
  31. id: 'wb-01',
  32. name: '丁博洋',
  33. },
  34. {
  35. id: 'wb-02',
  36. name: '丁博洋',
  37. },
  38. ];
  39. /* 将数据一行一行添加到sheet对象中 */
  40. data.forEach((item) => sheet.addRow(item));
  41. /* 遍历工作表的行row */
  42. sheet.eachRow((row, rowNumber) => {
  43. /* 遍历工作表的列cell */
  44. row.eachCell((cell, colNumber) => {
  45. // 设置第一行样式
  46. if (rowNumber === 1) {
  47. // 设置对齐样式
  48. cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
  49. // 设置字体样式
  50. cell.font = { bold: true, size: 14, name: 'Arial' };
  51. // 设置背景样式
  52. cell.fill = {
  53. type: 'pattern',
  54. pattern: 'solid',
  55. fgColor: { argb: 'FF5050E6' },
  56. };
  57. }
  58. // 设置边框
  59. cell.border = {
  60. top: { style: 'thin' },
  61. left: { style: 'thin' },
  62. bottom: { style: 'thin' },
  63. right: { style: 'thin' },
  64. };
  65. // 设置列宽
  66. // sheet.getColumn(colNumber).width = 25;
  67. });
  68. // 设置行高
  69. row.height = 25;
  70. });
  71. /* 将工作表转为 buffer 对象 */
  72. const buffer = await workbook.xlsx.writeBuffer();
  73. /* 将 buffer 装化成blob对象 */
  74. var blob = new Blob([buffer], {
  75. type: 'application/octet-stream',
  76. });
  77. /* 下载 blob 文件 */
  78. openDownloadDialog(blob, `模板.xlsx`);
  79. }
  80. // 将blob对象创建bloburl,然后用a标签实现弹出下载框
  81. function openDownloadDialog(blob, fileName) {
  82. const link = document.createElement('a');
  83. link.href = window.URL.createObjectURL(blob);
  84. link.download = fileName;
  85. link.click();
  86. window.URL.revokeObjectURL(link.href);
  87. }

excel转json

注意:exceljs 在浏览器端是不能操作文件,在nodejs项目中就可以使用它来读取、编辑.xlsx文件

参考文档