我正在尝试使用 ExcelJS 导出格式化的 excel 文件,而 writeFile 方法根本不起作用。调用函数时出现以下异常:
Uncaught TypeError: fs.createWriteStream is not a function
我的 javascript 是使用 browserify.js 捆绑的。这是我的源代码:
索引.html
<!DOCTYPE html>
<head>
<title>Test Excel JS</title>
<meta charset="utf-8">
<meta name="description" content="">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div>
<label>Test</label>
<button onclick="test()">Test this Stuff and Check your console log</button>
</div>
<script src="bundle.js"></script>
<script>
var test = function(){
writeFile();
};
</script>
</body>
</html>
app.js(由 browserify 捆绑到 bundle.js 中)
'use strict';
global.Excel = require('../node_modules/exceljs/dist/es5/exceljs.browser');
global.isRowBold = function(excelRow){
return excelRow.getCell('name').value === "Jeff";
};
global.getRowColor = function(excelRow){
return excelRow.getCell('color').value;
};
global.getCellColor = function(excelRow, cell){
return (excelRow.getCell('name').value === 'John' && cell.value === 0)? 'orange' : excelRow.getCell('color').value;
};
global.getFont = function(isBold, color){
return {
name: 'Arial Black',
color: color,
family: 2,
size: 14,
bold: isBold
};
};
global.getTestHeader = function(){
return [
{key: "id", header: "Id"},
{key: "name", header: "Name", width: 32},
{key: "color", header: "Color", width: 10}
];
};
global.getTestData = function(){
return [
{
id: 0,
name: "John",
color: "green"
},
{
id: 1,
name: "Rehan",
color: "blue"
},
{
id: 2,
name: "Jeff",
color: "yellow"
}
];
};
global.generateTestFile = function(){
var workbook = new Excel.Workbook();
workbook.creator = "Generated";
workbook.lastModifiedBy = "Generated";
workbook.created = new Date();
workbook.modified = new Date();
var worksheet = workbook.addWorksheet('Sheet 1');
//Set Column Headers
worksheet.columns = getTestHeader();
//Add Rows
var testData = getTestData();
var length = testData.length;
for(var i = 0; i < length; i++){
worksheet.addRow(testData[i]);
}
//Format Rows
worksheet.eachRow(function(row, rowNumber){
var isBold = isRowBold(row);
row.eachCell(function(cell, colNumber){
var cellColor = getCellColor(row, cell);
cell.font = getFont(isBold, cellColor);
});
});
//workbook.commit();
return workbook;
};
global.writeFile = function(){
var workbook = generateTestFile();
workbook.xlsx.writeFile('./output/newtestfile.xlsx')
.then(function() {
console.log('Done Writing file');
});
};