Tsuna
Tsuna

Reputation: 2196

csv export with symbol # as content ends the export

I have successfully exported my data as csv which worked great until there is a # character which messed up the exporting. It stopped the exporting anything after #. When I open the file, I can see that it's giving a newline then stopped.

I already added quotations to the text fields because of the need to export symbols such as , which works fine.

Can someone give me suggestions of why meeting # would give such reaction and way to solve it?

removing # is the least option to think of, would really prefer to keep the # I tried replacing # as ascii \u0023 which gives me no luck

How I get the text

const getDiv = bodyCellLabelClass.querySelectorAll('div');
const innerTxt = getDiv[ 0 ].innerText;
result.push(`"${innerTxt}"`);

sample of result would look like if I console.log

[""$41.67"", ""9/9/2018"", ""10/9/2018"", ""9/9/2018"", ""#111"", ""3/11/2019""]
[""$41.67"", ""9/9/2018"", ""10/9/2018"", ""9/9/2018"", ""3"", ""3/11/2019""]

but when I open the csv it'll look like

$41.67, 9/9/2018, 10/9/2018, 9/9/2018, '↵' nothing after

this is how the export csv looks like

export class ExportUtil {
    // export file, default excel
    public static spreadsheet( rows, full_filename = 'test.xls' ): any {

        let content = `data:application/vnd.ms-excel;charset=utf-8;`;
        rows.forEach(function ( rowArray ) {
            const row = rowArray.join(',');
            content += row + '\r\n';
        });

        console.log(content, 'inside spreadsheet content');

        const encodedUri = encodeURI(content);
        const link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', `${full_filename}`);
        document.body.appendChild(link); // Required for FF

        link.click(); // This will download the data file named "my_data.csv".
    }
}

Thanks in advance for any help and suggestions.

Upvotes: 2

Views: 248

Answers (1)

Dora
Dora

Reputation: 6990

try using Blob

export class ExportUtil {
    // export file, default excel
    public static spreadsheet( rows, full_filename = 'test.xls' ): any {

        let content = '';
        rows.forEach(function ( rowArray ) {
            const row = rowArray.join(',');
            content += row + '\r\n';
        });

        console.log(content, 'inside spreadsheet content');

        const blob = new Blob([ content ], { type: 'application/vnd.ms-excel;charset=utf-8;' });
        const url = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `${full_filename}`);
        document.body.appendChild(link); // Required for FF

        link.click(); // This will download the data file named "my_data.csv".
    }
}

Upvotes: 1

Related Questions