我有一个对象数组。默认情况下,sheet_to_json使用对象键作为标题。 但是,我需要重命名这些标头,而无需显式修改我的对象数组。
这可能吗?
答案 0 :(得分:9)
在下面替换最后一行。
XLSX.utils.sheet_add_json(ws, data, {skipHeader: true, origin: "A2"});
答案 1 :(得分:2)
我解决了这个问题,因为上述两种方法都不适合我
let EXCEL_EXTENSION = '.xlsx';
let worksheet: XLSX.WorkSheet;
let customHeader = true;
let sheetName = 'My Sheet 1';
if (customHeader) {
const headers: any = { Cust: 'Customer Name', Addr1: 'Address 1' };
this.data.unshift(headers); // if custom header, then make sure first row of data is custom header
worksheet = XLSX.utils.json_to_sheet(json, { skipHeader: true });
} else {
worksheet = XLSX.utils.json_to_sheet(json);
}
const workbook = XLSX.utils.book_new();
const fileName = 'myExcelFile_Export_' + moment().format('MM-DD-YYYY_hh:mm:ss').toString() + EXCEL_EXTENSION;
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
XLSX.writeFile(workbook, fileName);
答案 2 :(得分:2)
我正在分享找到的解决方案
// Using same variables as the above answer
var Heading = [
["FirstName", "Last Name", "Email"],
];
var Data = [
{firstName:"Jack", lastName: "Sparrow", email: "abc@example.com"},
{firstName:"Harry", lastName: "Potter", email: "abc@example.com"},
];
//Had to create a new workbook and then add the header
const ws = XLSX.utils.book_new();
XLSX.utils.sheet_add_aoa(ws, Heading);
//Starting in the second row to avoid overriding and skipping headers
XLSX.utils.sheet_add_json(ws, Data, { origin: 'A2', skipHeader: true });
答案 3 :(得分:0)
您可以使用XLSX.utils.aoa_to_sheet
添加标题。
例如:
// Do mind! it is array of array
var Heading = [
["FirstName", "Last Name", "Email"],
];
var Data = [
{firstName:"Jack", lastName: "Sparrow", email: "abc@example.com"},
{firstName:"Harry", lastName: "Potter", email: "abc@example.com"},
];
var ws = XLSX.utils.aoa_to_sheet(Heading);
XLSX.utils.sheet_add_json(ws, Data);
答案 4 :(得分:0)
这对我有用:
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.json_to_sheet(json_data, { origin: 'A2', skipHeader: true });
XLSX.utils.sheet_add_aoa(ws, headings); //heading: array of arrays
XLSX.utils.book_append_sheet(wb, ws);
XLSX.writeFile(wb, filename + '.xlsx')