Vue 使用 xlsx 插件导出 excel 文件

安装与引入

安装

csharp 复制代码
npm install xlsx
npm install file-saver
# 或者
yarn add xlsx
yarn add file-saver

引入

javascript 复制代码
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver'

基本功能

读取 Excel 文件

ini 复制代码
// 读取文件内容
const workbook = XLSX.readFile('path/to/file.xlsx');

// 获取第一个工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];

// 将工作表转换为 JSON 格式
const data = XLSX.utils.sheet_to_json(worksheet);
console.log(data);

写入 Excel 文件

ini 复制代码
// 创建工作簿
const workbook = XLSX.utils.book_new();

// 创建工作表
const data = [
  ['Name', 'Age', 'Email'],
  ['Alice', 25, 'alice@example.com'],
  ['Bob', 30, 'bob@example.com']
];
const worksheet = XLSX.utils.aoa_to_sheet(data);

// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

// 导出文件
XLSX.writeFile(workbook, 'output.xlsx');

高级功能

自定义样式

ini 复制代码
// 创建样式
const ws = XLSX.utils.aoa_to_sheet(data);
const wscols = [
  { wch: 15 },
  { wch: 10 },
  { wch: 30 }
];
ws['!cols'] = wscols;

// 添加样式
const cell = ws['A1'];
cell.s = {
  font: { bold: true },
  fill: { fgColor: { rgb: 'FF0000' } }
};

合并单元格

yaml 复制代码
// 合并单元格
ws['!merges'] = [
  { s: { r: 0, c: 0 }, e: { r: 0, c: 2 } } // 合并 A1:C1
];

添加水印

lua 复制代码
// 添加水印
XLSX.utils.sheet_add_aoa(ws, [['Watermark']], { origin: -1 });

使用示例

导出数据到 Excel 方法

javascript 复制代码
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

export function exportJsonToExcel(options) {
  // 默认配置
  const defaultOptions = {
    sheetName: 'Sheet1',
    autoWidth: true,
    watermark: ''
  };
  const { header, data, filename, sheetName, autoWidth, watermark } = {
    ...defaultOptions,
    ...options
  };

  // 1. 创建工作簿
  const wb = XLSX.utils.book_new();

  // 2. 处理数据(添加表头)
  const exportData = [header, ...data];

  // 3. 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(exportData);

  // 4. 自动设置列宽
  if (autoWidth) {
    const colWidths = header.map((_, colIndex) => {
      return {
        wch: Math.max(
          ...exportData.map(row => {
            const cellValue = row[colIndex];
            if (cellValue == null) return 10;
            return String(cellValue).replace(/[^\x00-\xff]/g, 'aa').length * 8 + 2;
          })
        )
      };
    });
    ws['!cols'] = colWidths;
  }

  // 5. 添加水印
  if (watermark) {
    if (!ws['!merges']) ws['!merges'] = [];
    ws['!merges'].push({
      s: { r: exportData.length + 1, c: 0 },
      e: { r: exportData.length + 1, c: header.length - 1 }
    });
    XLSX.utils.sheet_add_aoa(ws, [[watermark]], { origin: -1 });
  }

  // 6. 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, sheetName);

  // 7. 导出文件
  const excelBuffer = XLSX.write(wb, {
    bookType: 'xlsx',
    type: 'array'
  });
  const blob = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  });
  FileSaver.saveAs(blob, `${filename}.xlsx`);
}

参数说明

header: 表头数组,包含列名。

data: 数据数组,包含要导出的数据。

filename: 导出的 Excel 文件名。

sheetName: 工作表名称,默认为 Sheet1。

autoWidth: 是否自动调整列宽,默认为 true。

watermark: 水印文本,默认为空字符串。

使用

ini 复制代码
import { exportJsonToExcel } from "@/utils/index";

// 导出Excel
const exportExcel = () => {
  const header = [
    "时间",
    "类型",
    "地址",
    "ID",
  ];
  const data = tableData.value.map((item) => [
    item.time,
    item.type,
    item.address,
    item.id,
  ]);

  exportJsonToExcel({
    header,
    data,
    filename: "excel名",
  });
};
相关推荐
踩着两条虫18 分钟前
我在浏览器里“盖”了一个村:Vue + Three.js 大屏开发踩坑记
前端·vue.js·three.js
高级程序源2 小时前
SSM仓储管理系统31582-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·flask·课程设计
溪语流沙2 小时前
【Web全栈进阶】前端世界观:现代工具链与框架为什么存在
前端·javascript·vue.js
WeiXin_DZbishe3 小时前
基于微信小程序的本地闲置物品交易平台-计算机毕设 附源码【课程设计】26825
vue.js·spring boot·python·微信小程序·架构·php·课程设计
高级程序源4 小时前
springboot本地生活服务平台33399-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·小程序·flask·课程设计
高级程序源4 小时前
springboot社区旧物回收管理系统25381-计算机课程设计、毕业设计
vue.js·spring boot·python·django·课程设计
高级程序源4 小时前
springboot大学生体测系统72170-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
WeiXin_DZbishe4 小时前
基于Node.js的马拉松赛事管理系统的设计与实现-计算机毕设 附源码【课程设计】90211
java·javascript·vue.js·python·php·课程设计
风早爽太5 小时前
Mac 搭建 Vue 开发环境
前端·vue.js
高级程序源5 小时前
springboot校园外卖平台13676-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·tomcat·maven·课程设计