“缓冲区”类型不可分配给“BlobPart”类型

Kum*_*mar 8 javascript typescript

blobType: string = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
  cols = ['Column1', 'Column2', 'Column3', 'Column4', 'Column5']
  data = [
    { col1: "a1", col2: "b1", col3: "c1", col4: "d1", col5: "e1" },
    { col1: "a2", col2: "b2", col3: "c2", col4: "d2", col5: "e2" },
    { col1: "a3", col2: "b3", col3: "c3", col4: "d3", col5: "e3" },
    { col1: "a4", col2: "b4", col3: "c4", col4: "d4", col5: "e4" },
    { col1: "a5", col2: "b5", col3: "c5", col4: "d5", col5: "e5" }
  ]
Run Code Online (Sandbox Code Playgroud)

这是我的方法

exportToExcel() {
    var workbook = new Excel.Workbook();
    workbook.creator = 'Web';
    workbook.lastModifiedBy = 'Web';
    workbook.created = new Date();
    workbook.modified = new Date();
    workbook.addWorksheet(this.sName, { views: [{state: 'frozen', ySplit: 3,
                                                  xSplit: 2, activeCell: 'A1', showGridLines: false}] });
    let sheet = workbook.getWorksheet(1);
    let head1 = ['Exported Data'];
    sheet.addRow(head1);
    sheet.addRow('');
    sheet.getRow(3).values = this.cols;
    sheet.columns = [
      { key: 'col1' },
      { key: 'col2' },
      { key: 'col3' },
      { key: 'col4' },
      { key: 'col5' }
    ];
    sheet.addRows(this.data);
    workbook.xlsx.writeBuffer().then(data => {
      console.log(data);
      const blob = new Blob([data], { type: this.blobType });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = this.excelFileName;
      a.click();
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

类型 'Buffer' 不能分配给类型 'BlobPart'。类型 'Buffer' 不能分配给类型 'Blob'。“缓冲区”类型中缺少属性“大小”。【2322】(参数)数据:Excel.Buffer

const blob = new Blob([data], { type: this.blobType }); 
Run Code Online (Sandbox Code Playgroud)

我在上面一行出错,我错过了什么吗??

小智 14

这解决了我的问题:

const blob = new Blob([data as BlobPart], {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
Run Code Online (Sandbox Code Playgroud)


Luc*_*cho 4

尝试将回调改为这样

workbook.xlsx.writeBuffer().then((data:ArrayBuffer) => {
    const blob = new Blob([data], { type: this.blobType });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = this.excelFileName;
    a.click();
})
Run Code Online (Sandbox Code Playgroud)

更新

如果你不能像这样转换它,那么在这个问题上有一个拉取请求在等待你,如果你不想等待,你可以做的是在为 Excel 导入的 index.d.ts 中手动更改它。 js