简体   繁体   中英

Convert a javascript object to CSV file

I have a script which reads a file line by line, generate an object with some fields from certain lines and now I want to put that generated object into a CSV file.

How can I do the following:

  1. From the script itself generate a CSV file

  2. Give initial fields (headers) to the file

  3. Update that file line by line (add to the file one line at a time)

Some clarifications, I don't know the size of the CSV in advance, so the file must by dynamically changed.

Thanks in advance.

Looking at what you have said:

  1. From the script itself generate a csv file

  2. Give initial fields (headers) to the file & 3. Update that file line by line (add to the file one line at a time)

    • Check out the node-csv-generate stream functionality to write individually line by line (ie inital headers first)

Now since you said you need to run it locally, I would recommend Rhino if just using JS but if node.js is required then check out Rhinodo . These will let you run the program locally on the JVM basically (you could call the JS from within Java if you wanted to).

To export the CSV file there are plenty examples online this SO thread being one... ie

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Where csvContent is the complete string of your csv. I am not sure how supported this is on Rhinodo , but I'm pretty sure it'll all work on Rhino .


If this is intended to be a purely desktop based application, I would look at using Java (or your preferred language Python or C# might be nicer depending on what you are used to :-) ) rather than JS if everything needs to be local and it intends on being widely used. That way you have a much cleaner interaction with the OS and a lot more control.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM