简体   繁体   中英

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?

First I think ł is a utf-8.

Try printing it in the browser, it may be the console that make it look like this

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM