最簡單導出table為excel表格並自定義表格樣式


普通方式

下包

npm i -S file-saver xlsx

在util文件夾新建類

建立to_xlsx.js

import FileSaver from 'file-saver';
import XLSX2 from 'xlsx';

class ToXlsx {
  // id指的是綁定數據的table的id,
  // title指的是導出表格的名稱,記得帶后綴xlsx,例如:title='重復導.xlsx';
  constructor (id, title) {
    this.id = id;
    this.title = title;
  }
  
  async createTable() {
    // 判斷要導出的節點中是否有fixed的表格,如果有,轉換excel時先將該dom移除,然后append回去,
    let fix = document.querySelector ('.el-table__fixed');
    let wb;
    if (fix) {
      wb = XLSX2.utils.table_to_book(document.querySelector(this.id).removeChild(fix));
      document.querySelector(this.id).appendChild(fix);
    } else {
      wb = XLSX2.utils.table_to_book(document.querySelector(this.id));
    }
  
    
    /* get binary string as output */
    let wBout = XLSX2.write(wb, {
      bookType: 'xlsx',
      bookSST: true,
      type: 'array'
    });
    try {
      FileSaver.saveAs(
        new Blob([wBout], {
          type: 'application/octet-stream'
        }),
        this.title
      );
    } catch (e) {
      if (typeof console !== 'undefined') console.log(e, wBout);
    }
    return wBout;
  }
}

export default ToXlsx

使用

在js頁面直接import,然后使用

import ToXlsx from "../../utils/to_xlsx";

// 參數1 表格id
// 參數2 保存的excel文件名
let xlsx = new ToXlsx('#table-data', '下載.xlsx');
xlsx.createNormalTable()

參考資料

element-ui的table導出數據時重復導出

自定義樣式

下包

npm i -S xlsx-style xlsx

xlsx-style報錯修改


這個時候需要修改源碼

在\node_modules\xlsx-style\dist\cpexcel.js 807行把 var cpt = require('./cpt' + 'able'); 改成 var cpt = cptable;

如果還報錯

在\node_modules\xlsx-style\ods.js 10行和13行把路徑改為 require('./ xlsx')

在util文件夾新建類

建立to_xlsx.js

import XLSX2 from 'xlsx';
import XLSX from 'xlsx-style';

class ToXlsx {
  // id指的是綁定數據的table的id,
  // title指的是導出表格的名稱,記得帶后綴xlsx,例如:title='重復導.xlsx';
  constructor (id, title) {
    this.id = id;
    this.title = title;
  }
  
  /**
   * 自定義表格
   * @returns {Promise<void>}
   */
  async createCustomizeTable() {
    let sheet = XLSX2.utils.table_to_sheet(document.querySelector(this.id));
    // 設置單個單元格樣式 ,A2對應的是excel表格的A2
    // sheet["A2"].s = {
    //   alignment: {
    //     horizontal: "center",
    //     vertical: "center",
    //     wrap_text: true
    //   }
    };
    
    // sheet居然是個對象,所以遍歷就用for in
    // 偷個懶,因為要所有的表格都居中,所以這里就用for in 遍歷設置了,如果只是單個設置,那就用上面的單獨設置就行
    for (let key in sheet){
      if (new RegExp('^[A-Za-z0-9]+$').exec(key)) {
        let cell = key.toString();
        sheet[cell].s = {
          alignment: {
            horizontal: "center", // 水平對齊-居中
            vertical: "center", // 垂直對齊-居中
            wrap_text: true
          }
        }
      }
    }
    
    // wpx 字段表示以像素為單位,wch 字段表示以字符為單位
    // 注意,必須從第一個開始設置,不能只設置單獨一個
    // !cows是列寬
    sheet['cols'] = [
          {wch: 16}, // A列
          {wch: 16}, // B列
          {wch: 16}, // C列
          {wch: 16}, // D列
    ];
   
    // !rows設置的行高
    sheet['!rows'] = [
          {wpx: 40,}, // 1行
          {wpx: 40}, // 2行
          {wpx: 40}, // 3行
          {wpx: 40}, // 4行
    ];
    try {
      this.openDownloadDialog(this.sheet2blob(sheet), this.title);
    } catch (e) {
     console.log('自定義表格報錯', e);
    }
  }
  
  /**
   * 將表轉換為最終excel文件的blob對象,並使用URL.createObjectUR下載它
   * @param sheet 表格配置項
   * @param sheetName 表格名稱
   * @returns {Blob}
   */
  sheet2blob(sheet, sheetName) {
    sheetName = sheetName || 'sheet1';
    let workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };
    workbook.Sheets[sheetName] = sheet; // 生成excel的配置項
    
    let wopts = {
      bookType: 'xlsx', // 要生成的文件類型
      bookSST: false, // 是否生成Shared String Table,官方解釋是,如果開啟生成速度會下降,但在低版本IOS設備上有更好的兼容性
      type: 'binary'
    };
    let wbout = XLSX.write(workbook, wopts);
    let blob = new Blob([s2ab(wbout)], {
      type: "application/octet-stream"
    }); // 字符串轉ArrayBuffer
    
    function s2ab(s) {
      let buf = new ArrayBuffer(s.length);
      let view = new Uint8Array(buf);
      for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    }
    return blob;
  }
  
  /**
   *
   * @param url 生成的文件
   * @param saveName 保存文件名稱
   */
  openDownloadDialog(url, saveName) {
    if (typeof url == 'object' && url instanceof Blob) {
      url = URL.createObjectURL(url); // 創建blob地址
    }
    let aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的屬性,指定保存文件名,可以不要后綴,注意,file:///模式下不會生效
    let event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
      event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
  }
}

export default ToXlsx

單元格樣式

設置單元格的樣式,就是設置工作表對象中的單元格對象的 s 屬性。這個屬性的值也是一個對象,它有五個屬性:fill、font、numFmt、alignment和border。

Cell styles are specified by a style object that roughly parallels the OpenXML structure. The style object has five
top-level attributes: fill, font, numFmt, alignment, and border.

Style Attribute Sub Attributes Values
fill patternType "solid" or "none"
fgColor COLOR_SPEC
bgColor COLOR_SPEC
font name "Calibri" // default
sz "11" // font size in points
color COLOR_SPEC
bold true or false
underline true or false
italic true or false
strike true or false
outline true or false
shadow true or false
vertAlign true or false
numFmt "0" // integer index to built in formats, see StyleBuilder.SSF property
"0.00%" // string matching a built-in format, see StyleBuilder.SSF
"0.0%" // string specifying a custom format
"0.00%;\\(0.00%\\);\\-;@" // string specifying a custom format, escaping special characters
"m/dd/yy" // string a date format using Excel's format notation
alignment vertical "bottom" or "center" or "top"
horizontal "bottom" or "center" or "top"
wrapText true or false
readingOrder 2 // for right-to-left
textRotation Number from 0 to 180 or 255 (default is 0)
90 is rotated up 90 degrees
45 is rotated up 45 degrees
135 is rotated down 45 degrees
180 is rotated down 180 degrees
255 is special, aligned vertically
border top { style: BORDER_STYLE, color: COLOR_SPEC }
bottom { style: BORDER_STYLE, color: COLOR_SPEC }
left { style: BORDER_STYLE, color: COLOR_SPEC }
right { style: BORDER_STYLE, color: COLOR_SPEC }
diagonal { style: BORDER_STYLE, color: COLOR_SPEC }
diagonalUp true or false
diagonalDown true or false

使用

在js頁面直接import,然后使用

import ToXlsx from "../../utils/to_xlsx";

// 參數1 表格id
// 參數2 保存的excel文件名
let xlsx = new ToXlsx('#table-data', '下載.xlsx');
xlsx.createCustomizeTable()

參考資料

使用js-xlsx純前端導出excel

JavaScript導出excel文件,並修改文件樣式

Export excel using js-xlsx pure front end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM