exceljs将json数据导出为excel

2 阅读2分钟
import ExcelJS from 'exceljs'
 exportExcel() {
        const formattedData = [{
            name1:'',
            type1:'',
            value1:'',
            min1:'',
            max1:'',
            des1:'',
            name2:'',
            type2:'',
            value2:'',
            min2:'',
            max2:'',
            des2:'',
            isDifferent:true
        }]
        // 创建工作簿和工作表
        const workbook = new ExcelJS.Workbook()
        const worksheet = workbook.addWorksheet('Sheet1')
        // 设置第一行表头
        worksheet.mergeCells('A1', 'F1') // 合并 A1 到 F1
        worksheet.mergeCells('G1', 'L1') // 合并 G1 到 L1

        worksheet.getCell('A1').value = this.oriTableData[0].recipe1Name
        worksheet.getCell('G1').value = this.oriTableData[0].recipe2Name

        // 设置第一行表头样式(居中对齐、加粗)
        worksheet.getCell('A1').alignment = { horizontal: 'center', vertical: 'middle' }
        worksheet.getCell('A1').font = { bold: true }
        worksheet.getCell('A1').fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFFFCC00' } // 设置背景色为黄色
        }

        worksheet.getCell('G1').alignment = { horizontal: 'center', vertical: 'middle' }
        worksheet.getCell('G1').font = { bold: true }
        worksheet.getCell('G1').fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFFFCC00' } // 设置背景色为黄色
        }
        // 设置第二行表头
        const secondHeader = [
          '参数名',
          '校验类型',
          '参数值',
          '最小值',
          '最大值',
          '描述',
          '参数名',
          '校验类型',
          '参数值',
          '最小值',
          '最大值',
          '描述'
        ]
        const headerRow = worksheet.addRow(secondHeader)
        // 设置第二行表头样式(背景色、加粗、居中)
        headerRow.eachCell((cell) => {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFCCE5FF' } // 设置背景色为浅蓝色
          }
          cell.font = { bold: true } // 加粗字体
          cell.alignment = { horizontal: 'center', vertical: 'middle' } // 居中对齐
        })

        // 插入数据到工作表
        formattedData.forEach((row) => {
          const excelRow = worksheet.addRow([
            row.recipe1ParamName,
            row.recipe1ValidateType,
            row.recipe1ParamValue,
            row.recipe1MinValue,
            row.recipe1MaxValue,
            row.recipe1Remark,
            row.recipe2ParamName,
            row.recipe2ValidateType,
            row.recipe2ParamValue,
            row.recipe2MinValue,
            row.recipe2MaxValue,
            row.recipe2Remark
          ])

          // 如果 isDifferent 为 true,将参数值标红
          if (row.isDifferent) {
            if (row.recipe1ParamValue) {
              excelRow.getCell(2).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(3).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(4).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(5).font = { color: { argb: 'FFFF0000' } } // 参数值标红
            }
            if (row.recipe2ParamValue) {
              excelRow.getCell(8).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(9).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(10).font = { color: { argb: 'FFFF0000' } } // 参数值标红
              excelRow.getCell(11).font = { color: { argb: 'FFFF0000' } } // 参数值标红
            }
          }
        })
        // 自动调整列宽
        worksheet.columns.forEach((column,index) => {
          console.log('🚀 ~ worksheet.columns.forEach ~ column,index:', column,index)
          let maxLength = 0
          column.eachCell({ includeEmpty: false }, (cell) => {
            if (cell.value) {
              const cellValue = cell.value.toString()
              maxLength = Math.max(maxLength, cellValue.length)
            }
          })
          if (index === 0 || index === 6){
            column.width = maxLength + 2 // 添加额外的宽度以适应单元格边距
          } else {
            column.width = 15
          }
        })
        // 导出为 Excel 文件
        workbook.xlsx
          .writeBuffer()
          .then((buffer) => {
            // 创建 Blob 对象
            const blob = new Blob([buffer], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            // 创建下载链接
            const link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.download = `${this.$moment().format('YYYY-MM-DD')}对比数据.xlsx` // 设置下载文件名
            link.click() // 触发下载
            URL.revokeObjectURL(link.href) // 释放 URL 对象
            link.remove()
          })
          .catch((err) => {
            console.error('导出失败:', err)
          })
      }