gpt4 book ai didi

javascript - 将 excel 中的多个对象数组导出为多个工作表

转载 作者:行者123 更新时间:2023-12-05 03:42:40 26 4
gpt4 key购买 nike

假设我有多个对象数组,

const books = [{"book":"harry","part":1},{"book":"harry","part":2},{"book":"harry","part":3}, 
{"book":"lotr","part":1},{"book":"lotr","part":2}]

const personDetails = [{"name":"ram","age":21},{"name":"jack","age":22},{"name":"ryan","age":45}];

我可以通过如下方法下载一个对象数组,

import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

function downloadExcel() {
const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const bookDetails = XLSX.utils.json_to_sheet(books);
const wb = { Sheets: { 'BookDet': bookDetails }, SheetNames: ['BookDet'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data1 = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data1, "BookDetail Summary.xlsx");
}

但是如何在 Excel 的不同工作表中导出多个对象数组。如果有人需要任何进一步的信息,请告诉我。

最佳答案

尝试使用 var wb = XLSX.utils.book_new(); 按以下方式创建工作簿。

使用 XLSX.utils.json_to_sheet 创建工作表并使用 XLSX.utils.book_append_sheet 将两个 worksheeet 对象附加到工作簿。

引用:https://www.npmjs.com/package/xlsx#working-with-the-workbook

import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

function downloadExcel() {

/* create a new blank workbook */
var wb = XLSX.utils.book_new();

/* create a worksheet for books */
var wsBooks = XLSX.utils.json_to_sheet(books);

/* Add the worksheet to the workbook */
XLSX.utils.book_append_sheet(wb, wsBooks, "Books");

/* create a worksheet for person details */
var wsPersonDetails = XLSX.utils.json_to_sheet(personDetails);

/* Add the worksheet to the workbook */
XLSX.utils.book_append_sheet(wb, wsPersonDetails, "PersonDetails");


const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data1 = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data1, "BookDetail Summary.xlsx");
}

关于javascript - 将 excel 中的多个对象数组导出为多个工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67156118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com