自学内容网 自学内容网

js把数据导出excel表格并给表格设置样式

1.用到xlsx-js-style库,在命令行中下载:

npm install xlsx-js-style

 2.使用

// 整理表格
const formatExcel = (data, name) => {

    // 创建一个新的工作簿
    const workbook = XLSXS.utils.book_new();

    // 创建数据
    const worksheetData = data;

    // 将数据转换为工作表
    const worksheet = XLSXS.utils.aoa_to_sheet(worksheetData);

    // 设置样式
    const style = {
        font: {
            name: 'Times New Roman',
            sz: 12,
            
            color: { rgb: '#000000' } // 
        },
        border: {
            top: { style: 'thin', color: { rgb: '#000000' } },
            bottom: { style: 'thin', color: { rgb: '#000000' } },
            left: { style: 'thin', color: { rgb: '#000000' } },
            right: { style: 'thin', color: { rgb: '#000000' } }
        },
        alignment: {
            horizontal: 'center',
            vertical: 'center'
        }
    }
    for (let i = 0; i <= data.length; i++) {
        console.log(worksheet['A' + (i + 1)]);

        if (worksheet['A' + (i + 1)]) worksheet['A' + (i + 1)].s = style;
        if (worksheet['B' + (i + 1)]) worksheet['B' + (i + 1)].s = style;
    }



    const cols = data[0].map(() => ({ wch: 17 })); // 根据需要调整宽度  
    worksheet['!cols'] = cols;
    const rows = Array(data.length + 1).fill({ hpx: 20 }); // +1 因为包括表头行,根据需要调整高度  
    worksheet['!rows'] = rows;
    // 将工作表添加到工作簿中
    XLSXS.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // 将工作簿导出为 Excel 文件
    XLSXS.writeFile(workbook, name);
}

let studentData = [
    ['姓名', '年龄'],//表头
    ['张三', '18岁'],
    ['李四', '19岁'],
];

formatExcel(studentData, '学生信息.xls')


原文地址:https://blog.csdn.net/qq_68155756/article/details/142754706

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!