1、先安装依赖:xlsx、xlsx-style、file-saver三个包

npm install xlsx xlsx-style file-saver

出现错误:

This relative module was not found:
* ./cptable in ./node_modules/xlsx-style/dist/cpexcel.js

解决:

找到node_modules/xlsx-style/dist/cpexcel.js文件搜索:

var cpt = require('./cpt' + 'able');

改成:
var cpt = cptable;

2、一个完整的实例:

<template>
  <div class="hello" style="text-align:center;padding:20px 10px;font-size:16px;">
    <p>Welcome to <a @click="exportExcel()">下载</a></p>
  </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import XLSX_STYLE from 'xlsx-style';
import { saveAs } from 'file-saver';
export default {
  name: 'HelloWorld',
  data () {
    return {
      showData:[
        {type:1,createdTime:222,logistNo:"大课间分数段赛覅u奥菲娜啥的都能常偶第四节佛安抚巾哦说打就打覅欧派",note:"科诞节福利卡仕达付款单撒胡覅u阿鹅胡覅是的你师的话副科老师"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
        {type:1,createdTime:222,logistNo:3,note:"asdfads"},
      ]
    }
  },
  methods:{
    exportExcel() {
      const data = this.showData.map(item => {
        return {
          '类型': item.type,
          '订单日期': item.createdTime,
          '订单号': item.logistNo,
          '备注': item.note,
        }
      });
      // 定义表头样式
      const headerStyle = {
        fill: {
          fgColor: { rgb: '0070C0' },
        },
        font: {
          color: { rgb: 'ffffff' },
          name: '微软雅黑',
          sz: 11,
          bold:true
        },
        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',
          wrapText: true,
        },
      };
      const contentStyle = {
        font: {
          name: '宋体',
          sz: 10,
        },
        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',
          wrapText: true,
        },
      };

      const worksheet = XLSX.utils.json_to_sheet(data);
      var wscols = [{ wch: 30 }, { wch: 70 }, { wch: 30 }]
      //var wsrows = [{ hpt: 20 }, { hpt: 30 }]
      worksheet['!cols'] = wscols
      //worksheet['!rows'] = wsrows

      worksheet['!freeze'] = {
        xSplit: ""+1,  //冻结列
        ySplit: ""+1,  //冻结行
        //topLeftCell: "A2",  //在未冻结区域的左上角显示的单元格,默认为第一个未冻结的单元格
        activePane:"bottomRight",
        state: "frozen"
      }

      // 将表头样式应用到 worksheet 对象中的表头单元格
      const headerRange = XLSX.utils.decode_range(worksheet['!ref']);
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const headerCell = XLSX.utils.encode_cell({ r: headerRange.s.r, c: col });
        worksheet[headerCell].s = headerStyle;
      }

      // 将内容样式应用到 worksheet 对象中的所有单元格
      const contentRange = XLSX.utils.decode_range(worksheet['!ref']);
      for (let row = contentRange.s.r + 1; row <= contentRange.e.r; row++) {
        for (let col = contentRange.s.c; col <= contentRange.e.c; col++) {
          const contentCell = XLSX.utils.encode_cell({ r: row, c: col });
          worksheet[contentCell].s = contentStyle;
        }
      }
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '数据导出');
      // 将 workbook 对象转换为二进制数据流并下载
      const wbout = XLSX_STYLE.write(workbook, { bookType:'xlsx',type:'binary'});
      const blob = new Blob([this.s2ab(wbout)],{type:'application/octet-stream'});
      saveAs(blob,'table.xlsx');
    },
    s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xFF;
      }
      return buf;
    },
  },
  mounted:function(){
  },
}
</script>

问题解决1:

行高的设置不起作用,是因为XLSX_STYLE包里面没有这个方法,但是xlsx里面有:

\node_modules\xlsx-style\xlsx.js

里面找到:write_ws_xml_data 函数注释掉

用这个里面的函数替换:

\node_modules\xlsx\xlsx.js

function write_ws_xml_data(ws, opts, idx, wb) {......}

同时根据报错,一起加入:

var DEF_PPI = 96, PPI = DEF_PPI;
function px2pt(px) { return px * 96 / PPI; }
function pt2px(pt) { return pt * PPI / 96; }
function write_ws_xml_data(ws, opts, idx, wb) {
var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
var dense = Array.isArray(ws);
var params = ({r:rr}), row, height = -1;
for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
for(R = range.s.r; R <= range.e.r; ++R) {
r = [];
rr = encode_row(R);
for(C = range.s.c; C <= range.e.c; ++C) {
ref = cols[C] + rr;
var _cell = dense ? (ws[R]||[])[C]: ws[ref];
if(_cell === undefined) continue;
if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
}
if(r.length > 0 || (rows && rows[R])) {
params = ({r:rr});
if(rows && rows[R]) {
row = rows[R];
if(row.hidden) params.hidden = 1;
height = -1;
if(row.hpx) height = px2pt(row.hpx);
else if(row.hpt) height = row.hpt;
if(height > -1) { params.ht = height; params.customHeight = 1; }
if(row.level) { params.outlineLevel = row.level; }
}
o[o.length] = (writextag('row', r.join(""), params));
}
}
if(rows) for(; R < rows.length; ++R) {
if(rows && rows[R]) {
params = ({r:R+1});
row = rows[R];
if(row.hidden) params.hidden = 1;
height = -1;
if (row.hpx) height = px2pt(row.hpx);
else if (row.hpt) height = row.hpt;
if (height > -1) { params.ht = height; params.customHeight = 1; }
if (row.level) { params.outlineLevel = row.level; }
o[o.length] = (writextag('row', "", params));
}
} return o.join("");
}

问题解决2:

冻结窗口不起作用,解决方法:

\node_modules\xlsx-style\xlsx.js 里面找到:

function write_ws_xml(idx, opts, wb)

注释掉:
// o[o.length] = writextag('sheetViews', sheetView); 修改成: var pane = null;
var freeze = ws['!freeze'];
// console.log(freeze)
if (freeze !== undefined) {
pane = writextag('pane', null, {
xSplit: freeze.xSplit, // 冻结列
ySplit: freeze.ySplit, // 冻结行
topLeftCell: freeze.topLeftCell, // 在未冻结区域的左上角显示的单元格,默认为第一个未冻结的单元格
activePane: freeze.activePane,
state: freeze.state || 'frozen'
})
}
console.log("ssss ok")
o[o.length]=writextag("sheetViews", writextag("sheetView", pane, sheetView), {});

可惜msexcel打不开,还没找到解决办法。

本文借鉴内容来自:

https://www.cnblogs.com/gaoxiong666/p/17434607.html

https://blog.csdn.net/cs23405/article/details/133772940

vue,js直接导出excel,xlsx的方法,XLSX_STYLE 行高设置失效的问题解决,冻结窗体修改支持的更多相关文章

  1. JS导入导出Excel表格的方法

    https://blog.csdn.net/aa122273328/article/details/50388673 导出 https://blog.csdn.net/qq_37281252/arti ...

  2. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  3. 【转】js 中导出excel 较长数字串会变为科学计数法

    [转]js 中导出excel 较长数字串会变成科学计数法 在做项目中,碰到如题的问题.比如要将居民的信息导出到excel中,居民的身份证号码因为长度过长(大于10位),excel会自动的将过长的数字串 ...

  4. 从SQL Server中导入/导出Excel的基本方法(转)

    从sql server中导入/导出 excel 的基本方法 /*=========== 导入/导出 excel 的基本方法 ===========*/ 从excel文档中,导入数据到sql数据库中,很 ...

  5. ASP.net中导出Excel的简单方法介绍

    下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...

  6. C# 使用Epplus导出Excel [4]:合并指定行

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  7. vue 纯前端导出 excel 表格

    在开发后台管理系统的时候,很多地方都要用到导出excel 表格,比如将table中的数据导出到本地,那么实现这种需求往往有两种方案: 一.后端开发一个下载链接,前端将这个链接放到 a 标签的 href ...

  8. vue+element 表格导出Excel文件

    https://www.cnblogs.com/bobodeboke/p/8867481.html  非常感谢 这个大佬 才让我搞到了Blob.js 和 Export2Excel.js 如果最后运行时 ...

  9. vue页面原样导出excel表格

    github地址:https://github.com/wuzhiaite/vue-samples 1.excel导出 做过业务系统的知道,进行涉及到excel的导出,列表数据动则几十万,但是也有一部 ...

  10. 导出excel的简单方法

    excel的操作,最常用的就是导出和导入,废话不多说上代码. 本例使用NPOI实现的,不喜勿喷哈.... /// <summary> /// 导出Excel /// </summar ...

随机推荐

  1. [NOI2007] 项链工厂 题解

    前言 题目链接:洛谷:Hydro & bzoj. 题意简述 yzh 喜欢写 DS 题!你要维护一个环: 顺时针移动 \(k\) 位: 翻转 \(2 \sim n\): 交换 \(i\) 与 \ ...

  2. Game of CS 题解

    前言 题目链接:洛谷:UVA. 题意简述 Jolly 和 Emily 在玩一个游戏.游戏在一棵编号为 \([0, n-1]\) 的有根树上进行,根节点是 \(0\),每条边都有一个长度,初始所有边都没 ...

  3. ffmpeg和ffplay常用指令

    FFmpeg 常见用法 1. 基本命令结构 ffmpeg [global_options] -i input_file [input_options] output_file [output_opti ...

  4. C语言的指定初始化

    ----------------版权声明:本文为CSDN博主「Supan-Yang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明.原文链接:https://blog ...

  5. Atcoder ABC296 F

    Atcoder ABC296 F F - Simultaneous Swap 链接: F - Simultaneous Swap (atcoder.jp) 简要题意: 问题陈述 给你两个 \(N\) ...

  6. jdk8的Steam流工作常用方法总结

    Steam流工作常用方法总结 收集list 以某几个字段为键以内容为list的map Map<String, List<TVoucherDetail>> tVoucherDet ...

  7. Dialog封装的消息映射(弄了好久终于弄过了,不是静态函数哦,和MFC一样,嘻嘻)

    前面弄的是全局的仿消息映射,现在这是封装到类中的消息映射,一直弄不明白,现在也不太明白,就是今天在看虚函数表的用法视频时有位老师用了个共有体转化全局函数为类成员函数,这就给我指了条明路,这不今晚又来弄 ...

  8. Terraform中的for_each和count

    通过Terraform创建云主机时,在某些业务场景下,一个机器需要挂载多个云盘,一般云厂商都是单独创建云主机和云硬盘然后通过attachment的资源去挂载,因此我们的模板大致如下: resource ...

  9. Redmi AX6000 刷 OpenWrt

    一直想尝试玩玩软路由,但是家里实在没有软路由的需求,外加不知道该入手什么机器来刷软路由,所以迟迟没有入手.最近研究生要开学了,但是学校的有线网要下载专用软件认证才能上网,终于找到合适的理由入手一款软路 ...

  10. Visual Studio Code 重置“不再询问”选项

    有一次使用 VS Code 重命名一个 Python 文件时,VS Code 询问"扩展'Python'希望通过移动此文件来进行重构更改".当时没有多想,选中"不再提问& ...