codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Export Objects Array as CSV using TypeScript

Changhui Xu
codeburst
Published in
2 min readMar 25, 2019

--

Photo by Carlos Muza on Unsplash

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.

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (1)

Write a response