【问题标题】:xlsx package:Write excel file to a custom pathxlsx包:将excel文件写入自定义路径
【发布时间】:2022-07-27 19:31:23
【问题描述】:

我正在尝试使用 xlsx 包将对象数组写入 excel。

我想将文件写入路径而不是当前目录

 const fileName ='ouptputs/test.xlsx'
const workSheet = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
                
 XLSX.utils.book_append_sheet(wb, workSheet,fileName);
 const s = XLSX.writeFile(wb, fileName,{
     type:"file"
 });

但是执行这个我得到了错误

工作表名称不能包含:\ / ? *

那么我如何指定路径而不是生成文件到当前目录

我在他们的文档 https://github.com/SheetJS/sheetjs#writing-options 中进行了搜索,但找不到有关自定义路径的文档

【问题讨论】:

  • 错误来自XLSX.utils.book_append_sheet(wb, workSheet,fileName);。如果您更正了工作表名称,那么您应该能够写入您所追求的路径
  • 谢谢解决问题,一个小问题,如果没有给出名字,工作表名称是什么??
  • 给它一个名字,只是不要使用变量文件名,因为它在路径中有一个斜杠
  • 例如XLSX.utils.book_append_sheet(wb, workSheet,'Sheet1');

标签: javascript node.js xlsx


【解决方案1】:

问题是当您将字符串作为文件名传递给 writeFile 函数时,它会尝试在当前目录中使用您提供的名称查找文件,但它包含“/”,文件名中不能出现该文件,因为它导致错误。

所以解决方案是使用“路径”库创建路径,例如见下面的代码

const path = require('path');

// You may need to use relative path in join function depending upon the working file location
const filePath = path.join(__dirname, 'ouptputs/test.xlsx'); // __dirname -> returns the current path of the working file
const workSheet = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
                
XLSX.utils.book_append_sheet(wb, workSheet, 'Sheet1'); // Sheet1 is the name of sheet that is created inside workbook
const s = XLSX.writeFile(wb, filePath, {
        bookType: 'xlsx',
        type: 'file'
});

希望它能帮助您或其他人。谢谢!

快乐编码:-)

【讨论】:

    猜你喜欢
    • 2018-04-20
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多