- const jsonData = Forguncy.CommandHelper.getVariableValue("array_1");
- const commentsData = Forguncy.CommandHelper.getVariableValue("obj");
- const button = document.createElement('button');
- button.textContent = 'Download Excel';
- button.style.position = 'fixed';
- button.style.top = '10px';
- button.style.right = '10px';
- button.style.zIndex = 1000;
- document.body.appendChild(button);
- // 引入 SheetJS 库
- const script = document.createElement('script');
- script.src = 'https://cdn.sheetjs.com/xlsx-0.18.5/package/dist/xlsx.full.min.js';
- script.onload = () => {
- // 点击按钮时生成并下载 Excel 文件
- button.addEventListener('click', () => {
- // 将 JSON 数据转换为工作表
- const worksheet = XLSX.utils.json_to_sheet(jsonData);
- // 为每个列标题添加相应的批注
- const headers = Object.keys(jsonData[0]);
- headers.forEach((header, index) => {
- const cellAddress = XLSX.utils.encode_cell({ c: index, r: 0 });
- const comment = commentsData[header];
- if (comment) {
- if (!worksheet[cellAddress].c) {
- worksheet[cellAddress].c = [];
- }
- worksheet[cellAddress].c.push({ t: comment, a: "Author" });
- }
- });
- // 创建工作簿并添加工作表
- const workbook = XLSX.utils.book_new();
- XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
- // 将工作簿转换为二进制数据
- const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
- // 创建 Blob 对象并触发下载
- const blob = new Blob([wbout], { type: 'application/octet-stream' });
- const url = URL.createObjectURL(blob);
- // 输出下载链接
- console.log('Download URL:', url);
- const link = document.createElement('a');
- link.href = url;
- link.download = 'output.xlsx';
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- });
- };
- document.body.appendChild(script);
复制代码
使用SheetJS库。第一个参数是数据数组,第二个参数是字段:批注 对象。
|