2

I have a problem I want according to a value put a red or green color at the line of my exel to download : How could I set a specify cell's color in a worksheet. here is the ts class that handles the exel format:

exelgest:

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { formatDate } from '@angular/common';
import { ExcelColMapper } from 'src/app/shared/services/excelexport/ExcelColMapper';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
const EXCEL_DATE_FORMAT = 'yyyyMMdd';
@Injectable({
  providedIn: 'root'
})

export class ExcelService {

  constructor() { }
  public exportAsExcelFile(json: any[], excelFileName: string): void {
    // liste des width des colonnes
    const wscols = [];
    Object.values(ExcelColMapper.keys).forEach(element => {
      wscols.push({ wch: element.length });
    });
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json, { dateNF: 'YYYYMMDD HH:mm:ss'});
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    for (let C = range.s.r, index = 0; C <= range.e.r; ++C, index++) {
      const col = XLSX.utils.encode_col(C) + '1';
      if (!worksheet[col]) { continue; }
      worksheet[col].v = Object.values(ExcelColMapper.keys)[index];
    }
    worksheet['!cols'] = wscols;
    worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3']);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE});
    FileSaver.saveAs(data, fileName + formatDate(new Date(), EXCEL_DATE_FORMAT, 'en') + EXCEL_EXTENSION);
  }


}

thanks

Ailyse Iremam
  • 21
  • 1
  • 6

1 Answers1

0
cell.s = {
    fill: {
        bgColor: {rgb: "${color_code}"}
    },
    font: {
        color: {rgb: "${hashed_color_code}"}
    },
}

Refer to official library document for more details: https://www.npmjs.com/package/xlsx-with-styles

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
Akshay
  • 1