vue导出excel、txt、csv文件

2023/09/13 11:36:41

基于xlsx、file-saver库导出excel、txt、csv文件

背景

  • 需求:提供网页excel、txt、csv下载功能;

代码

  • xlsx
npm install -g xlsx@0.16.0 --save
import * as XLSX from "xlsx";
createExcel(name, data) {
  // 获取当前日期时间
  const now = new Date();

  // 构建文件名
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");

  const fileName = `job_${name}${year}${month}${day}.xlsx`;

  console.log(fileName); // 输出类似于 "20230828.xlsx"

  // 创建工作簿和工作表
  // 数据为json格式
  const ws = XLSX.utils.json_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // Sheet1 是工作表的名称

  // 将工作簿写入文件
  XLSX.writeFile(wb, fileName); // 文件名为 example.xlsx
}
  • txt
npm install --save file-saver
import { saveAs } from "file-saver";
createTXT(name, data) {
  // 获取当前日期时间
  const now = new Date();

  // 构建文件名
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");

  const fileName = `job_${name}${year}${month}${day}.txt`;

    // data为需要输入的字符串,注意需要添加[]
  const file = new File([data], fileName, {
    type: "text/plain;charset=utf-8",
  });
  saveAs(file);
}
  • csv:与txt方法相同
createCSV(name, data) {
  // 获取当前日期时间
  const now = new Date();

  // 构建文件名
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");

  const fileName = `job_${name}${year}${month}${day}.csv`;

  // 步骤 2: 将数据转换为 CSV 字符串
  data = data.map((row) => row.join(",")).join("\n");

  const file = new File([data], fileName, {
    type: "text/csv",
  });
  saveAs(file);
}