How to export CSV files preserving enconding in Excel
The way you can preserve your encondig in an Excel file
is to use a BOM_ORDER_MARK
which is a character used by Excel to know the file encondig.
You can create a utility function to download a CSV file like this:
const BYTE_ORDER_MARK = "%EF%BB%BF";
export default function downloadCsv(csv: string, fileName: string) {
const anchor = Object.assign(document.createElement("a"), {
href: `data:text/csv;charset=utf-8,${BYTE_ORDER_MARK}` + encodeURI(csv),
download: `${fileName}.csv`,
});
anchor.click();
}
To handle .csv
files, Microsoft Excel uses the List separator defined in Windows Regional settings.
In North America and some other countries, the default list separator is a comma, so you get CSV comma delimited.
In European countries, a comma is reserved for the decimal symbol, and the list separator is generally set to semicolon. That is why the result is CSV semicolon delimited.
You can configure the separator used in an CSV file by adding this as the first line:
sep=,
I've noticed that adding the sep line will make enconding break, so it's better not to add.