3

我正在使用exceljs并尝试在单元格中写入值,但它不起作用。但是workbook.xlsx.readFile(filename)正在工作,但workbook.xlsx.writeFile(filename)不会。

这是我的代码:-

var Excel = require('exceljs');
var fs = require('fs')
module.exports.summary = function(req, res, next) {
try {
    var filename = process.cwd() + '/template/report/summary.xlsx';
    var workbook = new Excel.Workbook();
    workbook.xlsx.writeFile(filename)
        .then(function() {
            var worksheet = workbook.getWorksheet(1);
            console.log('worksheet',worksheet);
            var row = worksheet.getRow(5);
            row.getCell('C').value = new Date();
            row.commit();
            worksheet.commit();

            workbook.commit().then(function() {
                console.log('xls file is written.');
            });
            res.json({ msg: done })
        });

 } catch (e) {
    next(e);
 }
}
4

3 回答 3

10

试试这段代码,希望对你有帮助

const excel = require('exceljs');

//Creating New Workbook 
var workbook = new excel.Workbook();

//Creating Sheet for that particular WorkBook
var sheetName = 'Sheet1';
var sheet = workbook.addWorksheet(sheetName);

//Header must be in below format
sheet.columns = [{key:"name", header:"name"}, {key: "age", header: "age"}];

//Data must be look like below, key of data must be match to header.
var data = [{name:"Kalai", age: 24}, {name:"Vignesh", age:24}];

//adding each in sheet
for(i in data){
  sheet.addRow(data[i]);
}

//Finally creating XLSX file
var fileName = "Sample.xlsx";
workbook.xlsx.writeFile(fileName).then(() => {
    callback(null);
});
于 2017-05-16T05:39:57.390 回答
0

在我的情况下,我的名称类似于“data2022/2023”,当我删除斜杠“data2020”时,主要问题是“/”。不知道为什么不能使用 unicoden"/"

于 2022-02-06T19:05:41.610 回答
0

不再支持writeFile,所以我建议你将它换成“writeBuffer”。这段代码对我有用:

const buffer = workbook.xlsx.writeBuffer();
const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
let EXCEL_EXTENSION = '.xlsx';
const blob= new Blob([buffer], {type: fileType});
saveAs(blob, 'filename' + EXCEL_EXTENSION);
于 2020-11-18T07:50:48.640 回答