Simple and easy to use|Pure front-end export excel + modification of common styles (vue + xlsx + xlsx-style)

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

It is inevitable to encounter the need to export EXCLE tables at work. This article only provides a quick introduction for Xiaobai. If you want to go deeper, please go to the official website


1. Installation dependencies

  1. file save
npm install file-saver --save
  1. Excel export
npm install xlsx --save
  1. Excel style modification - no need to import if style modification is not required
npm install xlsx-style --save

After introducing xlsx-style , there will be This relative module was not found:./cptable in ./node_modules/[email protected]@xlsx-style/dist/cpexcel.js error

Error solution

  1. Find the line 807 in \node_modules\xlsx-style\dist\cpexcel.js var cpt = require('./cpt' + 'able');and replace it with var cpt = cptable;save and continue.
  2. configureWebpackAdditions in vue.config.js
externals: {
    
    
     './cptable': 'var cptable'
   }

2. Use steps

1. Export and save function description

Create the toExcel.js file
with the following code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2. Read data

The code is as follows (example):

import XLSX from 'xlsx'
// 样式按需引入
import XLSXD from 'xlsx-style'
// 保存文件
import {
    
     saveAs } from 'file-saver'

// excel数据处理
export function toExcel(data) {
    
    
  // 生成数据表对象
  let wb = XLSX.utils.book_new()
  // 获取sheet页名称
  let sheets = Object.keys(data)
  sheets.forEach(sheet => {
    
    
    if (data[sheet].data && data[sheet].data.length > 0) {
    
    
      // 生成Sheet页
      wb.SheetNames.push(sheet)
      // 倒入数据
      wb.Sheets[sheet] = XLSX.utils.aoa_to_sheet(data[sheet].data)
      // 如果存在合并信息则存储合并单元格
      if(data[sheet].merges) {
    
    
        wb.Sheets[sheet]['!merges'] = data[sheet].merges
      }
      // 如果存在列宽信息,则调整列宽
      if(data[sheet].cols) {
    
    
        wb.Sheets[sheet]['!cols'] = data[sheet].cols
      }
    }
  })
  // 如果不需要引入样式,则使用   
  // let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary'})
  let wbout = XLSXD.write(wb, {
    
     bookType: 'xlsx', type: 'binary', bookSST: true, cellStyles: true})
  return wbout
}

//输出Excel
export function outputExcel(s) {
    
    
  let buf = new ArrayBuffer(s.length) //convert s to arrayBuffer
  let view = new Uint8Array(buf)  //create uint8array as viewer
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF //convert to octet
  return buf
}

// 传入xlsx对象和文件名称,导出文件
export function downLoadXlsx(wbout, fileName) {
    
    
  saveAs(new Blob([outputExcel(wbout)], {
    
     type: 'application/octet-stream' }), fileName+'.xlsx')
}

3. toExcel parameter transfer instructions

let data = {
    
    
  // 'xxx'为sheet页名称,需要多少sheet页就写多少个对象
  'xxx': {
    
    
    // 数据列表
    data: [
      // 每一个数组是一行数据
      [],
      [],
      // ...,
      [
        {
    
    
          v: '数据值 例如:表头1、123',
          t: '内行: b: Boolean, e: Error n: Number d: Date S text z: Stub', // 非强制
          s: '单元格样式' // 非强制
          // ...其余的不讲了
        },
        ]
    ],
    // 合并单元格
    merges: [
      {
    
    
        // 开始位置 c: col, r: row
        s: {
    
     c: 0, r: 0 },
        // 结束为止
        e: {
    
     c: 0, r: 0 }
      }
    ],
    // 列宽调整
    cols: [{
    
    wch: 20}]
  }
}

example:

let data = {
    
    
  // 'xxx'为sheet页名称,需要多少sheet页就写多少个对象
  '测试sheet1': {
    
    
    // 数据列表
    data: [
      // 每一个数组是一行数据
      [‘这里是表头’, '', '', ''],
      ['第一列', '第二列', '第三例', '第四列'],
      [
        {
    
    
          v: '张三',
          s: {
    
    
          	// 背景色
	        fill: {
    
    
	          fgColor: {
    
     rgb: 'FFFF00' }
	        },
	        // 边框
	        border: {
    
    
	          top: {
    
     style: 'thin', },
	          left: {
    
     style: 'thin', },
	          right: {
    
     style: 'thin', },
	          bottom: {
    
     style: 'thin', }
	        },
	        // 居中
	        alignment: {
    
    
	          horizontal: 'center',
	          vertical: 'center',
	          wrapText: true,
	        },
	        // 字体
	        font: {
    
    
	          bold: true,
	        }
	      }
        },
      ]
    ],
    // 合并单元格
    merges: [
      {
    
    
        // 开始位置 c: col, r: row
        s: {
    
     c: 0, r: 0 },
        // 结束为止
        e: {
    
     c: 0, r: 4 }
      }
    ],
    // 列宽调整
    cols: [{
    
    wch: 20}]
  }
}

Guess you like

Origin blog.csdn.net/YIGE_MO/article/details/128920696