Import and export data in CSV in Angular.
In this article, we will create an algorithm for importing and exporting data in CSV. We have two model arrays with those models we will import in a CSV file.
To save an array in CSV. We need to take all property names from the first object in the array. Those names became column names in the first row of the CSV file. Then we need to get all property values from each object in the array. Every object is one row, values are separated by a comma.
Obviously, when we do export we reverse an algorithm. We split the text into rows then on values.
But we have a small problem. When we save an array in CSV we convert every object property into a string. When we import from a CSV every value is a string. What if the value must be a number or boolean? How can we define the right type?
We can create a constructor in our type. This constructor will give us information about the type of property.
The constructor of the class we are gonna use in a new method of export data. This method will determine the property type of the class and will convert the value to the right type.
As a result, we can import and export simple and complex types.
If you need to take a close look at the project here is the link.
Originally published at http://tomorrowmeannever.wordpress.com on March 6, 2022.