<myTable 
:data="tableData"
:columns="columns"
/>
<button @click='exportxlsx'>导出</button>
import * as XLSX from "xlsx";
import XLSXJSStyle from "xlsx-js-style";

const colums = ref([
{
      title: "Name",
      key: "name",
       rowSpan: (rowData, rowIndex) => (rowIndex === 0 ? 2 : 1),
    },
    {
      title: "Age",
      key: "age",
      colSpan: (rowData, rowIndex) => (rowIndex === 0 ? 2 : 1)
    },
    {
      title: "Address",
      key: "address",
      children:[
	]
    },
])


const tableData=ref([
 {
      key: 0,
      name: "John Brown",
      age: 32,
      address: "New York No. 1 Lake Park",
    },
    {
      key: 1,
      name: "Jim Green",
      age: 42,
      address: "London No. 1 Lake Park",
    },
    {
      key: 2,
      name: "Joe Black",
      age: 32,
      address: "Sidney No. 1 Lake Park",
    }
])

/**
 * 将表格导出成excel
 * @param params
 * {columns,tableData,sheetName,headRowLength,filename}
 *
 */
 const exportTableFile = (params={}) => {
      if (!params) return;
      // n-data-table 的 columns
      if (!Array.isArray(params.columns)) return ;
      // n-data-table 的 data
      if (!Array.isArray(params.tableData)) return ;
      // 导出xlsx的 sheet名称
      if (!params.sheetName) params.sheetName = 'sheet';
      //表头加粗时,使用到的 表头占用的行数
      if (!params.headRowLength || typeof params.headRowLength!=='number') params.headRowLength = 1;
      //
      if (!params.filename) params.filename='测试';

    const table = document.createElement("table");
    try {
      table.appendChild(
        document.querySelector(".n-data-table-thead").cloneNode(true)
      );
      table.appendChild(
        document.querySelector(".n-data-table-tbody").cloneNode(true)
      );
    } catch (e) {}
    const book = XLSX.utils.book_new();
    // {raw: true}属性表示导出数据是未加工的,数字过长不会变成科学计数法,百分数不会变成小数等
    const sheet = XLSX.utils.table_to_sheet(table, { raw: true });
  
    // 定义样式
    const styleObj = {
      font: {
        name: "宋体",      //字体名称 默认值 是Calibri
        sz: 11,            //字号
        // italic: false, //倾斜
        // underline: false,  //下划线
        // bold: true,             //加粗
        color: {
            rgb: "000000",      //字体颜色
        },
      },
      alignment: { vertical: "center", horizontal: "center" },
        border:{
            top: { style: 'thin' },
            left: { style: 'thin' },
            bottom: { style: 'thin' },
            right: { style: 'thin' }
        }
    };
    //设置单元格 样式
    for (let key in sheet) {
      let length = (key + "").length;
      let newKey = (key + "").slice(0, length - 1); // 截取到倒数第二位
      if (key.indexOf("!") === -1) {
        // 给表头设置背景色
        // 判断截取的key是否是字母开头并且最后一位等于1 符合条件则设置背景色
          //headRowLength 表示表头占用几行
        if (/^[A-Za-z]+$/.test(newKey) && (key[length - 1] >0)  && (key[length - 1] <=params.headRowLength )) {
          sheet[key] = {
            ...sheet[key],
            s: {
              ...styleObj,
              fill: { fgColor: { rgb: "C0C0C0" } },
            },
              // 空数据时,t的的值不是s,背景色和边框不生效,强制设置为s
              t:'s'
          };
        } else {
          sheet[key] = {
            ...sheet[key],
            s: styleObj,
              // 空数据时,t的的值不是s,背景色和边框不生效,强制设置为s
            t:'s'
          };
        }
      }
    }
    //获取每一列的宽度,并在导出的时候进行设置
    let wscols = [
      // 每列不同宽度px
      { wpx: 60 },
      // {wch: 26},
    ];
    wscols = params.columns.reduce((cur, pre) => {
      if (pre.children) {
        return [
          ...cur,
          ...pre.children.reduce((c, p) => [...c, { wpx: p.width || "200" }], []),
        ];
      }
      return [...cur, { wpx: pre.width || "200" }];
    }, []);
    sheet["!cols"] = wscols;
  
    //设置每行高度并在导出时设置
    let wsrows = [
      { hpx: 30 }, // 每行固定高度px
    ];
    for (let i = 0; i <= params.tableData; i++) {
      // total  列表条数
      wsrows.push({ hpx: 20 });
    }
    sheet["!rows"] = wsrows;
  
    XLSXJSStyle.utils.book_append_sheet(book, sheet, params.sheetName);
    // bookType:文件类型,可以是xlsx、xlsm、xlsb、xls,解决.xls格式时只能导出256列,超出的将会丢失
    XLSXJSStyle.writeFile(book, `${params.filename}.xlsx`, { bookType: "xlsx" });
    table.remove(); //释放内存占用
  };

const exportxlsx=()=>{
exportTableFile({
columns:columns.value,
tableData:tableData.value,
sheetName:'班级信息',
headRowLength:1,// 表头着重渲染 表头一共占用几行
filename:'下载的文件名'
});
}

GitHub 加速计划 / vu / vue
100
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:18 天前 )
9e887079 [skip ci] 11 个月前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐