node.js - 如何从nodejs终端下载excel文件

标签 node.js mocha.js

我是nodejs新手。需要你的帮助。我想从 nodejs 终端下载一个 excel 文件并将其转换为 csv(例如,mocha online.js)。注意:我不想通过浏览器执行此操作。

下面是我正在编写的一个脚本,用于下载并转换为 csv。没有错误,也没有预期的结果:

online.js

if (typeof require !== 'undefined') XLSX = require('xlsx');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

/* set up XMLHttpRequest */
var url = "http://oss.sheetjs.com/js-xlsx/test_files/formula_stress_test_ajax.xlsx";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
describe('suite', function () {
    it('case', function () {
    var arraybuffer = xhr.response;

    /* convert data to binary string */
    var data = new Uint8Array(arraybuffer);
    var arr = new Array();
    for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
    var bstr = arr.join("");

    /* Call XLSX */
    var sheetName = 'Database';
    var workbook = XLSX.read(bstr, { type: "binary" });
    var worksheet = workbook.Sheets[sheetName];
    var csv = XLSX.utils.sheet_to_csv(worksheet);
    console.log(csv);
    xhr.send();  
    //.... perform validations here using the csv data 
    });
})}

最佳答案

我自己尝试了这段代码,似乎它可以工作,唯一的是我花了 15 分钟试图理解为什么我的开放式办公室无法打开该文件,我最终明白他们正在发送一个 zip 文件...这是完整的代码,http get 函数的文档在这里 http.get

您可以使用 request模块,但它不是原生的,但请求更容易。

享受吧!

const url = 'http://oss.sheetjs.com/js-xlsx/test_files/formula_stress_test_ajax.xlsx'
const http = require('http')
const fs = require('fs')

http.get(url, (res) => {
    debugger
    const {
        statusCode
    } = res;
    const contentType = res.headers['content-type'];
    console.log(`The type of the file is : ${contentType}`)
    let error;
    if (statusCode !== 200) {
        error = new Error(`Request Failed.\n` +
            `Status Code: ${statusCode}`);
    }
    if (error) {
        console.error(error.message);
        // consume response data to free up memory
        res.resume();
        return;
    }
    res.setEncoding('binary');
    let rawData = '';
    res.on('data', (chunk) => {
        rawData += chunk;
    });
    res.on('end', () => {
        try {
            const parsedData = xlsxToCSVFunction(rawData);
            // And / Or just put it in a file
            fs.writeFileSync('fileName.zip', rawData, 'binary')
                // console.log(parsedData);
        } catch (e) {
            console.error(e.message);
        }
    });
}).on('error', (e) => {
    console.error(`Got error: ${e.message}`);
});


function xlsxToCSVFunction(rawData) {
    return rawData //you should return the csv file here whatever your tools are
}

关于node.js - 如何从nodejs终端下载excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43562382/

相关文章:

node.js - 如何使用 Sequelize 连接 3 个表?

javascript - 我在以下 chai Expect 中收到断言错误

typescript - VSCode : Tests won't proceed after using executeCommand to open a sample project

node.js - 使用虚拟数据库在自己的环境中测试express.js应用程序

node.js - AssertionError 使 Mocha 崩溃

javascript - 如何返回在我的 vuejs 组件上更新的数据

javascript - 启动 Node 应用程序时出错 - MEAN Stack

node.js - 删除 CloudWatch 事件规则仍将其附加到 lambda

MySQL 存储函数返回对象而不是整数

javascript - 如何从 promise 中获取值(value)。回调返回未定义