Simple y fácil de usar | Excel de exportación de front-end puro + modificación de estilos comunes (vue + xlsx + xlsx-style)

Consejo: Una vez escrito el artículo, la tabla de contenido se puede generar automáticamente. Cómo generarla puede consultar el documento de ayuda a la derecha.


prefacio

Es inevitable encontrar la necesidad de exportar tablas EXCLE en el trabajo. Este artículo solo proporciona una breve introducción a Xiaobai. Si desea profundizar más, vaya al sitio web oficial.


1. Dependencias de instalación

  1. guardar archivo
npm install file-saver --save
  1. Exportación de Excel
npm install xlsx --save
  1. Modificación de estilo de Excel: no es necesario importar si no se requiere modificación de estilo
npm install xlsx-style --save

Después de introducir xlsx-style , habrá un error Este módulo relativo no se encontró:./cptable en ./node_modules/[email protected]@xlsx-style/dist/cpexcel.js

Solución de errores

  1. Busque la línea 807 en \node_modules\xlsx-style\dist\cpexcel.js var cpt = require('./cpt' + 'able');y reemplácela con var cpt = cptable;guardar y continuar.
  2. configureWebpackAdiciones en vue.config.js
externals: {
    
    
     './cptable': 'var cptable'
   }

2. Utilice pasos

1. Exportar y guardar la descripción de la función.

Cree el archivo toExcel.js
con el siguiente código:

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. Leer datos

El código es el siguiente (ejemplo):

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. aInstrucciones de transferencia de parámetros de Excel

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}]
  }
}

ejemplo:

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}]
  }
}

Supongo que te gusta

Origin blog.csdn.net/YIGE_MO/article/details/128920696
Recomendado
Clasificación