Search code examples
javascriptcsvutf-8exceljs

How to read special characters from .csv files in JavaScript


I want to read .csv files which contains special characters (polish language).

I'm using ExcelJs to read .csv:

    var workbook = new Excel.Workbook();
    workbook.csv.readFile(uploadsPath + "/" + filename, {delimiter: ';'})
        .then(function (worksheet) {
            var worksheet = workbook.getWorksheet(1);

            console.log(worksheet.getRow(3).getCell(7).value);
        });
}

With this code I'm getting "Wroc�aw" instead of "Wrocław".

I tried using encoding:

    var workbook = new Excel.Workbook();
    workbook.csv.readFile(uploadsPath + "/" + filename, {encoding: 'utf-16le'})
        .then(function (worksheet) {
            var worksheet = workbook.getWorksheet(1);

            console.log(worksheet.getRow(3).getCell(7).value);
        });
}

But then I'm getting this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "buf" argument must be one of type Buffer, TypedArray, or DataView. Received type object

How to deal with it?


Solution

  • Ok, I found a simple solution.

    I created function

    function changeEncoding(path) {
        var buffer = fs.readFileSync(path);
        var output = iconv.encode(iconv.decode(buffer, "win1250"), "utf-8");
        fs.writeFileSync(path, output);
    }
    

    I simply reading file, and with the help of iconv-lite, firstly decoding from win1250 and then saving the file with utf-8 encoding.