[英]how to write all array elements to excel file using exceljs in nodejs
[英]ExcelJS write an array to excel
我正在使用一个 API,我在其中获取信息并将其存储在一个名为 res 的数组中。 我希望将此数组写入 excel 文件。 数组中的第一个信息应该在 A2 中,第二个信息在 B2 中,依此类推。
这是我的代码:
const api2 = require("fordonsuppgifter-api-wrapper");
(async () => {
console.log("fetching vehicle info");
var res = await api2.GetVehicleInformation("XMP433");
console.log(res);
})();
const Excel = require('exceljs');
const fileName = 'simple.xlsx';
const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');
const r3 = ws.getRow(3);
r3.values = [1, 2, 3, 4, 5, 6];
wb.xlsx
.writeFile(fileName)
.then(() => {
console.log('file created');
})
.catch(err => {
console.log(err.message);
});
API 正在运行,但我无法将其写入 excel 文件。
您可以使用这两个组合调用创建 excel 文件。 exceljs
库需要移动单元格写入功能
ws.getCell(<cell_address>).value = <assigned_value>
cell_address 向下移动需要增加数字(增加行号)
示例:下一行的 A1 -> A2。
columnName()
可以从整数转换为 Excel 列地址。
例子
columnName(1) -> A
columnName(2) -> B
您需要将Object()
从 JSON 转换为Object
类型然后可以获取 JSON key
的列表
Object.keys(carData)
const Excel = require('exceljs');
const api2 = require("fordonsuppgifter-api-wrapper");
const columnName = (index) => {
var cname = String.fromCharCode(65 + ((index - 1) % 26));
if (index > 26)
cname = String.fromCharCode(64 + (index - 1) / 26) + cname;
return cname;
}
const getCarInformation = async (keyword) => {
try {
const res = await api2.GetVehicleInformation(keyword);
return Promise.resolve(res);
} catch (error) {
return Promise.reject(error);
}
}
// Search car by keyword
getCarInformation("XMP433")
.then((carData) => {
const fileName = 'simple.xlsx';
const workbook = new Excel.Workbook();
// make workbook with 'car' name
const ws = workbook.addWorksheet("car")
// Start Cell A1 for title column
let headerColumn = 1
let section_number = 1
for (let key in carData) {
// title column, example : A1 = Sammanfattning
ws.getCell(columnName(headerColumn) + String(section_number)).value = key
subItems = carData[key]
row_number = section_number
for (let subKey in subItems) {
// Sub title Cell Bx, example : B1 = Registreringsnummer
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = subKey
// value Cell Cx, example : C1 = '(2*) XMP433'
ws.getCell(columnName(headerColumn + 2) + String(row_number)).value = subItems[subKey]
row_number++;
}
// Jump to next title
section_number = section_number + Object.keys(carData[key]).length;
}
workbook.xlsx
.writeFile(fileName)
.then(() => {
console.log('file created');
})
.catch(err => {
console.log(err.message);
});
})
.catch(err => {
console.log(err.message);
});
simple.xlsx
保存文件后,您需要单击标题以扩展列的宽度以适合其内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.