Create csv file and store data

How can I create a csv file and store data in it? Please give me a simple code.

Hi @siam009 , the simplest way you could achieve this is to convert a nested JS array into a CSV-string then write that string to a CSV file in the plugin folder.
Staff update: Refer to this answer to understand why the following example won’t work.

For example:

const rows = [
  ["doc1", "layer1", "size1"],
  ["doc1", "layer2", "size2"]
];
const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;

const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()
  • We loop through the rows entries, join each row’s entries and append them to the csvContent string with newline characters.
  • Call encodeURI with the csvContent string to encode it to a URL encoded string.

And finally, we can download the string as a file with window.open but you wouldn’t be able to set the filename that way.

  • to set the file name, we can create an invisible link and click on it programmatically.

Let me know if this helps!

Best,

Amanda

1 Like

No csv file is saving. Note that I am using mac m1

The method I suggested above is probably not suitable for anything other than the most basic use base anyways. What I would do to save a CSV file that I could write in is use getFileForSaving() to get/create a file that is read/write. Once it returns the file you want to write into, you can use a library like csv-writer to write JS arrays into CSV format.

2 Likes

You’ll need to use getFileForSaving – UXP panels don’t initiate a download flow when a link is clicked like browser clients or CEP do (this is something the browser agent provides for you, and not a default JS behavior that you can rely on in all JS environments).

3 Likes