Angular 6-格式化导出Excel工作表

时间:2018-10-25 13:34:33

标签: excel typescript angular6 xlsx

我想在Excel工作表中应用样式来表示数据。这是我的代码

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

const EXCEL_TYPE = 'application/vnd.openxmlformats- 
officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable()
export class ExcelService {

constructor() { }

public exportAsExcelFile(json: any[], excelFileName: string): void {

var aoa = this.create2DArray(json, excelFileName);
const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(aoa);
console.log('worksheet',worksheet);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);

}

我可以下载文件和数据,但不能以格式化的格式下载。

格式化Excel-

Excel formatting example

任何人都可以在同一方面提供一些信息。

谢谢。

2 个答案:

答案 0 :(得分:1)

您好,您可以使用“ exceljs”库为xlsx工作表设置样式。   您可以根据需要设置样式或自定义表格。

  

步骤1:npm安装exceljs,   npm安装文件保护程序

     

第2步:从“ exceljs”导入{工作簿};    从'file-saver'导入*作为fs;

在要使用它们的ts文件中添加这两个变量

  

const EXCEL_TYPE ='application / vnd.openxmlformatsofficedocument.spreadsheetml.sheet; charset = UTF-8';

     

const EXCEL_EXTENSION ='.xlsx';

     

第3步:在tsconfig.json中添加以下代码

"paths": {
      "exceljs": [
        "node_modules/exceljs/dist/exceljs.min"
      ]
    }

public exportAsExcelFile(json: any[], excelFileName: string, headersArray: any[]): void {
    //Excel Title, Header, Data
    const header = headersArray;
    const data = json;
    //Create workbook and worksheet
    let workbook = new Workbook();
    let worksheet = workbook.addWorksheet(excelFileName);
    //Add Header Row
    let headerRow = worksheet.addRow(header);
    // Cell Style : Fill and Border
    headerRow.eachCell((cell, number) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFFF00' },
        bgColor: { argb: 'FF0000FF' }
      }
      cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } }
    })
    // Add Data and Conditional Formatting
    data.forEach((element) => {
      let eachRow = [];
      headersArray.forEach((headers) => {
        eachRow.push(element[headers])
      })
      if (element.isDeleted === "Y") {
        let deletedRow = worksheet.addRow(eachRow);
        deletedRow.eachCell((cell, number) => {
          cell.font = { name: 'Calibri', family: 4, size: 11, bold: false, strike: true };
        })
      } else {
        worksheet.addRow(eachRow);
      }
    })
    worksheet.getColumn(3).width = 15;
    worksheet.getColumn(4).width = 20;
    worksheet.getColumn(5).width = 30;
    worksheet.getColumn(6).width = 30;
    worksheet.getColumn(7).width = 10;
    worksheet.addRow([]);
    //Generate Excel File with given name
    workbook.xlsx.writeBuffer().then((data) => {
      let blob = new Blob([data], { type: EXCEL_TYPE });
      fs.saveAs(blob, excelFileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
    })
  }

答案 1 :(得分:0)

您可以使用exceljs库对表进行样式化。在我的一种实现中,我不得不使单元标题成为大写。我添加了以下代码段,以在阅读工作表之后通过循环遍历循环来将标题格式化为大写。

public exportAsExcelFile(json, excelFileName: string): void {
  const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
  var range = XLSX.utils.decode_range(worksheet['!ref']);
  for (var C = range.s.r; C <= range.e.c; ++C) {
    var address = XLSX.utils.encode_col(C) + '1'; // <-- first row, column number C
    if (!worksheet[address]) continue;
    worksheet[address].v = worksheet[address].v.toUpperCase();
  }
  const workbook: XLSX.WorkBook = {
    Sheets: { data: worksheet },
    SheetNames: ['data'],
  };
  const excelBuffer: any = XLSX.write(workbook, {
    bookType: 'xlsx',
    type: 'array',
  });
  this.saveAsExcelFile(excelBuffer, excelFileName);
}