Vue3 export form excel (support multiple sheet pages), and customize the export style

Early preparation

npm install file-saver

npm install xlsx

npm install xlsx-js-style

Let me first talk about why you choose to use the xlsx-js-style plug-in to set the style of exporting excel. Due to the needs of the project, I found a lot of articles on the Internet about exporting custom styles of excel. The most commonly used plug-in is xlsx-style. There is a troublesome problem that an error will be reported when referencing xlsx-style. This is It has been written on the official website. The first solution is to change the source code in node-module, and the second is to modify the configuration file, but I think these two methods are not a long-term solution, and xlsx-style has not been updated and maintained for a long time. Whether other problems will arise. I have also tried the solution on the official website, and installed other plug-ins such as xlsx-style-medalsoft , but it still reports an error, maybe it does not support vue3??? It needs to be studied...so I discarded xlsx-style

html code

The table that needs to be exported should be added with the id name on the table tag or el-table tag (I use the table tag here based on the requirements and the data returned by the interface. If the interface data is an ordinary array object and does not need to be customized The title is the same as el-table), and you need to use the id name to find the corresponding table when exporting . The data of these tables comes from the interface, so you don’t need to paste the code directly. Use v-show="false" to hide the form because the form does not need to be displayed on the page, but only needs to be exported with the help of this form. It should be noted that v-if cannot be used here, v-if="false" will not render the element, and this element will not be found when exporting.

Click the method to bind the export all button

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import { exportExcel } from '@/utils/exportExcel'

// 全部導出
const allExport = async () => {
  ElMessageBox.confirm('確定導出所有會計報表?', '導出提示', {
    confirmButtonText: '確定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const allTable = [
        {
          eleName: '#detail', //要导出的表格id
          title: '明細分類賬表' //sheet页名称
        },
        {
          eleName: '#trial',
          title: '試算平衡表'
        },
        {
          eleName: '#balance',
          title: '資產負債表'
        },
        {
          eleName: '#gainLoss',
          title: '損益表'
        }
      ]
      exportExcel(allTable, '總表') //导出的excel的名称
    })
    .catch(() => {})
}
</script>

/utils/exportExcel

import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'//这是vue3导入XLSX的方法
import XLSXS from 'xlsx-js-style'

// 導出Excel文件的方法
export function exportExcel(allTable, excelName) {
  const xlsxParam = { raw: true } // 导出的内容只做解析,不进行格式转换 如果不设置该属性80%可能导出的是0.8 可自行测试
  
  let wb = XLSX.utils.book_new()
  // 循环添加每一个表格/sheet (如果是只有一个sheet页的话就不需要循环,直接添加进去就可以了)
  for (const item of allTable) {
      let sheet = XLSX.utils.table_to_sheet(document.querySelector(item.eleName), xlsxParam)
      XLSX.utils.book_append_sheet(wb, sheet, item.title)
  }
  //console.log(wb) //打印查看wb的结构 看下图

  // 循环找到对应的单元格修改样式
  for (const key in wb.Sheets) {
    if (key == '損益表') {
      for (const k in wb.Sheets[key]) {
        // 非!开头的属性都是单元格
        if (!k.startsWith('!')) {
          const td = wb.Sheets[key][k] 
          //td每一个是单元格对象 v:单元格内容 t:单元格内容类型如string s:单元格样式
          if (td.v.includes('(')) {
            // 設置字體顔色 帶括號的數字比如(1,000.00)改成紅色
            td.s = {
              font: {
                color: { rgb: 'ff0000' }
                // name: '仿宋',
                // sz: 20,
                // bold: true,
              }
              // border: {
                // top: {
                  // style: 'thin',
                  // color: { rgb: '000000' }
                // }
              // }
            }
          }
        }
      }
    }
  }

  const wbout = XLSXS.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${excelName}.xlsx`)
  } catch (e) {
    if (typeof console !== 'undefined') {
      console.log(e, wbout)
    }
  }
  return wbout
}

The result printed by wb:

 

The structure of the cell after adding the style:

Exported effect:

cell style

To set the style of a cell is to set the s attribute of the cell object in the worksheet object. The value of this property is an object with five properties: alignment, border, fill, font, and numFmt. GitHub - gitbrent/xlsx-js-style: SheetJS Community Edition + Basic Cell Styles

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/126009473