1

任何人都可以帮助我加载带有 excel 数据的数组并将其作为函数返回吗?这是我的初始代码:

var excel = require('exceljs');

var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');

function signIn(){
    var SignIn = [];
    wb.xlsx.readFile(filePath).then(function(){
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
    });
    return SignIn
}
4

1 回答 1

0

Workbook.readFile 是异步的,您需要使用回调或承诺类型的方法。使用 Promise,我们可以尝试:

var excel = require('exceljs');
var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');

function signIn() {
    var SignIn = [];
    return wb.xlsx.readFile(filePath).then( () => {
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
        return SignIn;
    });
}

async function testReadData() {
    try {
        let data = await signIn();
        console.log('testReadData: Loaded data: ', data);
    } catch (error) {
        console.error('testReadData: Error occurred: ', error);
    }
}
testReadData();

或者您可以使用回调类型方法:

function signInWithCallback(callback) {
    var SignIn = [];
    wb.xlsx.readFile(filePath).then(function(){
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
        callback(SignIn);
    });
}

signInWithCallback((data) => console.log('Callback: Data: ', data));
于 2018-08-23T14:51:16.403 回答