当前位置: 首页 > news >正文

传统项目纯前端实现导出excel之xlsx.bundle.js

传统项目纯前端实现导出excel之xlsx.js

 
    自从vue问世后,使得前端开发更加简洁从容,极大的丰富组件样式和页面渲染效果,使得前端功能的可扩展性得到极大地加强。虽然vue的使用对于前后端分离的项目对于功能实现与扩展有了质的飞跃,但仍旧有些传统的项目步履维艰,功能延伸性开发束手束脚,效率相对低下,就比如在某些mvc+jsp页面要实现excel的导出功能,有时候会后端框架封装的约束,这个时候直接在前端实现excel导出,就变的极为方便。本文介绍一款js插件——xlsx.bundle.js

一、简介

xlsx.bundle.js 是一个与 xlsx 或 xlsx-js-style 等库相关的 JavaScript 文件,通常用于在前端实现 Excel 文件的读取、创建和导出等功能。

二、功能和用途

  1. 文件读取与写入:xlsx.bundle.js 提供了读取和写入 Excel 文件的功能,支持多种格式,如 .xlsx、.xls、.csv 等。
  2. 表格样式设置:结合 xlsx-js-style,可以为表格设置样式,例如字体、对齐方式、边框、背景颜色等。
  3. 单元格合并:支持合并单元格操作,可以通过指定范围来合并单元格。
  4. 数据处理:可以对表格中的数据进行处理,例如添加公式、数据验证等。
  5. 前端导出:可以直接在前端将数据导出为 Excel 文件,无需后端支持

三、excel导出示例

3.1 xlsx.bundle.js 下载及引入

下载到本地后进行使用,从github上下载,然后把其中的文件xlsx.bundle.js 拷贝你的项目,在项目中引入即可使用。

<script src="dist/xlsx.bundle.js"></script>

3.2 xlsx.bundle.js 使用

1.获取dom元素

const tree = mini.get("excel-dom");

2.展开数据
由于此处要导出的数据是一个树形的列表,因此需要将数据进行展开为同一维度。如果使用的数据不是树形列表,可以忽略此步骤。

    const nodes = tree.getData(true); // 获取所有展开的节点

    // 展平数据
    const flatNodes = flattenTasks(nodes);

3、转为二维数组并添加序号

  // 转换为二维数组,并添加序号
    let data = [
        ["易耗物资消耗汇总统计表", "", "", "", "", "", "", "", ""],
        ["类型:", "", "", "", "部门:", "", "", "统计期:", ""],
        ["序号", "编号", "名称", "规格型号", "单位", "平均单价", "去年同期消耗数量", "本期消耗数量", "本期与去年同期比较"]
    ];


    flatNodes.forEach(function (node, index) {
        data.push([index + 1, node.code, node.name, node.type, node.unit, node.price, node.lastCostNum, node.currentCostNum, node.differenceValue]);
    });

4.创建工作簿并调整列宽

 // 创建工作簿对象
    const workbook = XLSX.utils.book_new();

    // 将二维数组转换为worksheet
    const worksheet = XLSX.utils.aoa_to_sheet(data);

    // 自动调整列宽
    autoFitColumns(worksheet, data);

5.表头合并

 // 定义表头合并区域
    worksheet['!merges'] = [
        {s: {r: 0, c: 0}, e: {r: 0, c: 8}}, // 序号
        {s: {r: 1, c: 1}, e: {r: 1, c: 3}}, // 横向合并(第一行的二三四列合并)
        {s: {r: 1, c: 5}, e: {r: 1, c: 6}}, // 横向合并 (第一行的六七两列合并)

    ];

s:表示开始,e:表示结束
r:表示行 (索引从0开始表示第一行) c:表示列(索引从0开始表示第一列)

6.excel行高设置

 // 动态设置行高
    let colWidths = worksheet['!cols'];
    worksheet['!rows'] = [];
    for (let i = 0; i < data.length; i++) {
        if (i == 0) {
            worksheet['!rows'].push({hpt: 35}); // 表头行
        } else if (i == 1) {
            worksheet['!rows'].push({hpt: 20});  // 第2行行高设置
        } else {
        //动态计算行高
            let calculateLen = 1;
            for (let j = 0; j < data[i].length; j++) {
                const cellValue = data[i][j] === null ? '' : data[i][j];
                const cellLength = calculateCellWidth((cellValue + ""));
                const colWidth = colWidths[j] ? colWidths[j].wch : 10;
                const lines = Math.ceil(cellLength / colWidth);
                const maxLines = Math.max(1, lines);
                calculateLen = calculateLen > maxLines ? calculateLen : maxLines;
            }
            worksheet['!rows'].push({hpt: 18 * calculateLen}); // 设置行高
        }
    }

7、设置所有单元格的边框样式和对齐方式

    // 设置所有单元格的边框样式和对齐方式
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    for (let R = range.s.r; R <= range.e.r; ++R) {
        for (let C = range.s.c; C <= range.e.c; ++C) {
            const cell_ref = XLSX.utils.encode_cell({r: R, c: C});
            if (!worksheet[cell_ref]) {
                continue;
            }

            // 设置单元格样式
            worksheet[cell_ref].s = {
                border: {
                    top: R >= 2 ? {style: "thin", color: {rgb: "000"}} : "",
                    bottom: R >= 2 ? {style: "thin", color: {rgb: "000"}} : "",
                    left: R >= 2 ? {style: "thin", color: {rgb: "000"}} : "",
                    right: R >= 2 ? {style: "thin", color: {rgb: "000"}} : ""
                },
                alignment: {
                    // horizontal: R === 0 || R === 2 || R === 3 ? 'center' : 'left', // 表头居中,数据区域左对齐
                    horizontal: (R === 0 || R === 2  || (cell_ref.startsWith('A') && cell_ref !== 'A2')) ? 'center' :
                        (cell_ref === 'A2' || cell_ref === 'E2' ||  cell_ref === 'H2') ? 'right' : 'left',
                    vertical: 'center', // 垂直对齐方式
                    wrapText: true // 启用自动换行
                },
                font: {
                    name: R == 1 ? '宋体' : 'Calibri', //第二行使用宋体,其他行使用Calibri
                    sz: R === 0 ? 16 : (R === 2 ) ? 14 : 12,
                    bold: R === 0 ? true : (cell_ref === 'A2' || cell_ref === 'E2' ||  cell_ref === 'H2') ? true : false,
                    color: {rgb: "000000"}
                },

            };
        }
    }

8、添加worksheet到workbook并输出文件

 // 添加worksheet到workbook
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    try {
        XLSX.writeFile(workbook, '易耗物资消耗汇总统计表.xlsx'); // 导出 workbook
    } catch (error) {
        console.error('Error writing Excel file:', error);
    }

9.其他相关函数


/**
 * 将嵌套的数组转换为平面列表
 * 该函数通过递归遍历每个任务及其子任务(如果存在),并将它们的信息提取到一个新的数组中
 * @param {Array} tasks - 嵌套的任务对象数组,每个任务对象可能包含一个子任务数组
 * @returns {Array} - 包含所有任务信息的平面列表数组,不包含任何嵌套结构
 */
function flattenTasks(tasks) {
    let flatList = [];
    tasks.forEach(task => {
        // 将当前任务的相关属性提取到一个新对象中,并添加到展平列表中
        flatList.push({
            id: task.id,
            code: task.code,
            name: task.name,
            type: task.type,
            unit: task.unit,
            price: task.price,
            lastCostNum: task.lastCostNum,
            currentCostNum: task.currentCostNum,
            differenceValue: task.differenceValue,
        });
        // 如果当前任务有子任务,则递归调用flattenTasks,并将结果合并到展平列表中
        if (task.children && task.children.length > 0) {
            flatList = flatList.concat(flattenTasks(task.children));
        }
    });
    return flatList;
}



/**
 * 自动调整列宽
 * @param ws 工作表
 * @param data 数据
 */
function autoFitColumns(ws, data) {
    const colWidths = data[0].map((_, i) => {
        return data.reduce((max, row) => {
            const cellValue = row[i] === null ? '' : row[i];
            const cellLength = calculateCellWidth(cellValue + "");
            return Math.max(max, cellLength);
        }, 10); // Minimum width of 10 characters
    });

//自定义列宽
    if(colWidths){
        colWidths[0] = 12;
        colWidths[1] = 15;
        colWidths[5] = 13;
        colWidths[6] = 24;
        colWidths[7] = 18;
        colWidths[8] = 24;
    }
    ws['!cols'] = colWidths.map(width => ({wch: width}));
}

/**
 * 计算单元格宽度
 * @param value 值
 * @returns {number} 列宽(磅)
 */
function calculateCellWidth(value) {
    // 判断是否为null或undefined
    if (value == null) {
        return 10;
    } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        // 中文的长度
        const chineseLength = value.match(/[\u4e00-\u9fa5]/g).length;
        // 其他不是中文的长度
        const otherLength = value.length - chineseLength;
        return chineseLength * 2.1 + otherLength * 1.1;
    } else {
        return value.toString().length * 1.1;
    }
}

导出效果如下
在这里插入图片描述

相关文章:

  • 无人机视觉定位,常用相机,及相机提供的数据信息
  • 系统架构设计师之系统设计模块笔记
  • Redis进阶--哨兵
  • 【Git】--- 多人协作实战场景
  • BFG Repo-Cleaner 教程:快速清理 Git 仓库中的敏感数据和大文件
  • Android InstalldNativeService::getAppSize源码分析
  • Ubuntu系统下的包管理器APT
  • Fay 数字人部署环境需求
  • Ubuntu下载火狐浏览器
  • Python学习笔记(9)关于元组
  • P1049 装箱问题
  • PPT处理控件Aspose.Slides教程:使用 Java 编程创建动画幻灯片
  • 解析Java包核心知识
  • 单链表——C语言实现
  • c++进阶--智能指针
  • 第十三天 - Ansible基础架构 - YAML语法与Playbook - 练习:批量配置部署
  • Kaggle-Digit Recognizer-(多分类+卷积神经网络CNN)
  • 集成学习+泰坦尼克号案例+红酒品质预测
  • pipe匿名管道实操(Linux)
  • SpringBoot集成Ollama本地模型