writeFile not woking in exceljs

给你一囗甜甜゛ 提交于 2021-02-07 20:14:33

问题


i am using exceljs and try to write value in a cell but it does not working. However workbook.xlsx.readFile(filename) is working but workbook.xlsx.writeFile(filename) won't.

Here is my code:-

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);
 }
}

回答1:


Try this code, Hope this will help you

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);
});



回答2:


writeFile is no longer supported, so I suggest you to exchange it for "writeBuffer". This code worked to me:

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);


来源:https://stackoverflow.com/questions/43279928/writefile-not-woking-in-exceljs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!