Franki1986
Franki1986

Reputation: 1436

Exceljs Angular 8 Change csv delimiter

I would like to use exceljs to write a csv file with writeBuffer. How can I change the csv delimiter. On github there was an issue that you have to do it with fast csv options. But first thing is that writeBuffer has no options parameter, and second the Interface for csv options has no delimiter Option.

var workbook = new ExcelJS.Workbook();    
  var worksheet = workbook.addWorksheet('Main sheet');
workbook.csv.writeBuffer().then(function(buffer) {
      saveAs(new Blob([buffer], { type: "application/octet-stream" }), "DataGrid.csv");
    });

Upvotes: 0

Views: 2166

Answers (2)

Wian du Plooy
Wian du Plooy

Reputation: 31

I know this is an old question, however, in case anyone else is looking for the same answer (with newer versions of the modules). This worked for me:

First import the required modules:

import { Workbook } from 'exceljs'; // (current version is 4.2.1)
import saveAs from 'file-saver'; // (current version is 2.0.5)

Then you can set the delimiter within the formatterOptions:

const workbook = new Workbook();
const worksheet = workbook.addWorksheet('Main sheet');

workbook.csv.writeBuffer({ formatterOptions: { delimiter: delimiter } })
.then((buffer: BlobPart) => {
    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'filename.csv');
})
.catch();

If you encounter an error during the build process of the app (e.g. Cannot find module 'stream'), you may need to add "node" to the "types" in the tsconfig.app.json file:

{
    "compilerOptions": {
        "types": ["node"]
    }
}

Upvotes: 3

Franki1986
Franki1986

Reputation: 1436

First thing, I am using exceljs version 1.12.2: I have seen that the barrell is not complete, so the declared method

function writeBuffer(options)

is not visible over the typings. So if you import exceljs like this:

import * as ExcelJS from 'exceljs';

You should call the method like this:

 let csv = workbook.csv as any; // workaround
 csv.writeBuffer({delimiter: ";"}).then(function(buffer) {
     saveAs(new Blob([buffer], { type: "application/octet-stream" }), "Data.csv");
 });

Upvotes: 0

Related Questions