Member-only story
Export Objects Array as CSV using TypeScript
End users might want to download data from a web page so that users can keep a copy of data or do some magic tricks in Excel. Today, I will show a way to export an array of objects as a CSV file using TypeScript. You can view the demo here.
Show me the code
The code snippet below shows a service class CsvDataService
which has a static method exportToCsv
.
The usage is very straightforward and is something like below. The method exportToCsv
takes two parameters, a file name string and an array of objects.
CsvDataService.exportToCsv(‘test.csv’, data);
The method exportToCsv
mainly contains 3 parts.
- Lines 3–5 are for “housekeeping”.
- Lines 6–22 contain the part that generates the CSV file content.
- Lines 24–39 contain the part to download the CSV file.
Caveats
- In line 6, we set the separator as
“,”
. We can choose other options, such as“|”
and“\t”
. However, I found that adding a white space after comma (“, ”
) didn’t work well. So, please pay attention to the separator setting. - Lines 8–22 iterate each object and its properties to generate the CSV content. The code takes care of escaping special characters, such as comma, quote and line breaking.
- Lines 14–15 handles Date values. If a property is of Date type, then we use a Locale String to represent its value. You can use
JSON.stringify()
method to convert Date values as well. - Line 24 constructs a
Blob
object from the CSV content for downloading. - Lines 25–39 handle downloading in different browsers.
This is a quick blog post. I hope the code is self-explanatory. And you can dig into more discussions in this StackOverflow question. Thanks for reading.