Simplest front-end export (vue + xlsx)

need

The export in the original project is an interface written by the back-end, and the content of a certain business page table needs to be exported to Excel from the front-end. It is necessary to export all data not the current page, and there are no other requirements.

Install

cnpm install xlsx --save-dev

cnpm install file-saver --save-dev

dev is added or not added as needed.

use

image.pngThe pop-up window page is paged as shown above, but all the data is required to export Excel, so write a separate value opacityof 0 el-tablefor export.

// .vue
// template
<el-table id="out-table" border :data="Pollutantlist" style="opacity:0;">
  <el-table-column
    v-for="coll in column"
    :key="coll.value"
    :label="coll.label"
    align="center"
    :prop="coll.value"
    :min-width="coll.width"
  >
    <template slot-scope="scope">
      ...
    </template>
  </el-table-column>
</el-table>

Pollutatlist为全部数据。(ps:由于涉及到接口数据的行转列,所以才有column的循环,这点可以忽略。)

// script 
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

// script (method)
handleExport(){//导出按钮
  /* 从表生成工作簿对象 */
  var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
  /* 获取二进制字符串作为输出 */
  var wbout = XLSXD.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array',
    cellStyles: true,
  })
  try {
    FileSaver.saveAs(
      // Blob 对象表示一个不可变、原始数据的类文件对象。
      // Blob 表示的不一定是JavaScript原生格式的数据。
      // File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
      // 返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
      new Blob([wbout], { type: 'application/octet-stream' }),
      // 设置导出文件名称
      'xxxx数据.xlsx'
    )
  } catch (e) {
    if (typeof console !== 'undefined') console.log(e, wbout)
  }
  return wbout
}
复制代码

over...

In this way, the styles are defaulted by xlsx after export, so in order to be consistent with the Excel results exported by the back-end interface in the project, a little style needs to be added. Here, according to the situation in the project, you need to set:

  1. Header background color and header text color.

The requirements are as follows: image.pngdo not be as follows: image.png2. Set the border
3. Set the font
4. Set the column width

add style

cnpm install xlsx-style --save-dev

//vue.config.js
module.export = {
...
    configureWebpack:{
        externals:{
          './cptable': 'var cptable'
        },
    }
...
}
复制代码

It must be configured here, otherwise an error will be reported. You can also change the source code processing. Since our company has more people involved and does not work in the same place, we do not change the source code. In addition, adjust the js.

// script 
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import XLSXD from 'xlsx-style' // 新增

// script (method)
1. handleExport(){
2.   var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
3.   let blocks = wb.Sheets[wb.SheetNames[0]];//注释一
4.   Object.keys(blocks).map((str)=>{
5.     let res = str.match(/^[A-Z]+1$/g);//注释二
6.     let cell = blocks[str];
7.     if(res){
8.       blocks['!cols'].push({wpx:cell.v.length*20+8});//注释三
9.       cell.s = {
10.         font: {
11.           name: 'Arial',
12.           bold: true,
13.           color: { rgb:"FFFFFFFF" },
14.           sz: 10
15.         },
16.         fill: { fgcolor:{ rgb:'FF808080'},fgColor:{ rgb:'FF808080'}},
17.         alignment: { horizontal:'center' },
18.         border: {
19.           top: { style: 'thin' },
20.           bottom: { style: 'thin' },
21.           left: { style: 'thin' },
22.           right: { style: 'thin' },
23.         }
24.       }
25.     }else if(str.indexOf('!')==-1){// 注释四
26.       cell.s = {
27.         font: {
28.           name: 'Arial',
29.           sz: 10
30.         },
31.         alignment: { horizontal:'center' },
32.         border: {
33.           top: { style: 'thin' },
34.           bottom: { style: 'thin' },
35.           left: { style: 'thin' },
36.           right: { style: 'thin' },
37.         }
38.       }
39.     }
40.   })
41.   var wbout = XLSXD.write(wb, {//这里是XLSXD
42.     bookType: 'xlsx',
43.     bookSST: true,
44.     type: 'buffer',//这里是buffer
45.     cellStyles: true,
46.   })
47.   try {
48.     FileSaver.saveAs(
49.       new Blob([wbout], { type: 'application/octet-stream' }),
50.       'xxxx数据.xlsx'
51.     )
52.   } catch (e) {
53.     if (typeof console !== 'undefined') console.log(e, wbout)
54.   }
55.   return wbout
56. }
复制代码

Note 1: Let's take a
look at 2the example of the first line of code wb:
image.png

image.png

Among them, SheetNamesthe name set representing Sheetsthe "worksheet" is the attribute set of the content of the "worksheet". SheetNames.Sheet1Below !colsrepresents a stored column object, !rowsrepresents a stored row object, and !refrepresents a sheet-wide string. The rest of the properties represent cells, which correspond to the locators at the top and left of the Excel page. For example, A2 means the first column and the second row. Some other properties can be found here .

Note 2:
In order to set the style for the header, match the SheetNames.Sheet1header according to the rules, set one style for the header, and set another style for other cells that are not headers. Styles are SheetNames.Sheet1mounted under the properties object under . For example, the A1 object indicates that the cell content (t) is a string, and the display value (v) is a mosaic.

v: value of cell
t: type of cell 'b' boolean, 'n' number, 'e' error, 's' string, 'd' date
s: style of cell

Note 3:
Set the column width, temporarily set the column width to the string length * 20 pixels. !colsThe required format is:[{wpx:20},...]

Note 4:
Remove non-cell attributes SheetNames.Sheet1under : !cols, !fullref, !ref,!rows

OVER !

Guess you like

Origin juejin.im/post/7086382246852034568