Question

In an angular project im trying to implement a function to generate a CSV file from an array of objects.

The array of objects populates a ng-Table so at first i tried to use: http://bazalt-cms.com/ng-table/example/15 This worked great in chrome, in IE it doesnt work at all though because it needs to use the download attribute...

Then i tried this approach

     var objArray = [
         { name: "Item 1", color: "Green", size: "X-Large" },
         { name: "Item 2", color: "Green", size: "X-Large" },
         { name: "Item 3", color: "Green", size: "X-Large" }];

    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
    }

But, now all the data of a row is in one single column. I want need the data on seperate columns.

Expected output (once opened in Excel)

enter image description here

Anyone got an idea how to do this?

Was it helpful?

Solution

This looks like an Excel question.

But, now all the data of a row is in one single column. I want need the data on seperate columns... (once opened in Excel)

You are creating the file like this: Convert JSON format to CSV format for MS Excel

The problem is that your file doesn't have a csv extension. Instead of double clicking the file or allowing IE to automatically open it, open Excel and choose File > Open. Browse to the file and click Open. This will invoke the Text Import wizard where you can specify comma as the delimeter.

Update
You can tell Excel how to process the file by adding "sep=," to the first line. In your code, add the following line after your loop:
str = 'sep=,\r\n' + str;

If you open the file in Notepad, it will look like this:
sep=,
name,color,size
Item 1,Green,X-Large
Item 2,Green,X-Large
Item 3,Green,X-Large

However, when the file is opened in Excel, only the headers and data will be present:
csv opened in Excel

Here is a demo, forked from Joseph Sturtevant's fiddle posted in the answers to the related question: http://jsfiddle.net/wittwerj/6JySt/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top