我尝试使用ExcelJS导出格式化的Excel文件,而writeFile方法根本不起作用。当我调用函数时,我得到以下异常:
Uncaught TypeError: fs.createWriteStream is not a function
我的javascript是使用browserify.js捆绑的。这是我的源代码:
的index.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');
});
};
答案 0 :(得分:0)
fs.createWriteStream
是一种用于Node.js(服务器)的方法。浏览器(客户端)无法使用这些方法。
答案 1 :(得分:0)
将writeFile更改为writeBuffer
使用文件保护程序
workbook.xlsx.writeBuffer()
.then(buffer => FileSaver.saveAs(new Blob([buffer]), `${Date.now()}_feedback.xlsx`))
.catch(err => console.log('Error writing excel export', err)