How do I export a csv file?
Following on from importing a csv file displaying it in a field or a data grid and renaming the headers this lesson will show you how to export the data to a csv file.
Exporting from a field
We will take as our starting point a stack set up with a field with csv data in it, as described in the lesson How do I rename the headers on a text file? Add another button to the interface and name it "export":
Scripting the export button
Exporting our data will be quite similar to importing with a couple of changes. We will use the ask file command, instead of answer file, as this allows the user to provide the name and location of a new file or choose an existing file. We also want to ensure that we save out as a csv file so we check the file extension of the selected file.
on mouseUp local tFileName, tFileContents ask file "Please choose a where you want to save the file" with type "Comma Separated Values|csv|TEXT" if the result is not "cancel" then put it into tFileName ## Ensure the file extension is csv set the itemDel to "." if item 2 of tFileName is not "csv" then put "csv" into item 2 of tFileName end if end if end mouseUp
Saving the data to file
As before we now have the location of the file we want to save our csv data into, all we have to do now is put the contents of the field into the file. Again we use the URL keyword, but this time we put the data into the url.
## Save the data out to file put field "text" into tFileContents put tFileContents into URL ("file:" & tFileName)
Exporting from a data grid
In the How do I rename the headers on a text file? lesson we imported our data and displayed it in a data grid. What if we want to export from a data grid? Again we can use the same LiveCode to get the file name, we just need to modify the LiveCode that saves the data.
Get the column names
Firstly we need to get the names of our columns, we get the data grid columns property, this is a line delimited list so we need to replace the item separators with commas:
put the dgProp[ "columns" ] of group "text" into tColumnTitles replace return with comma in tColumnTitles
Get the data
Next we need the data, we get the dgText of the data grid, the item separator for dgText is tab so we replace tabs with commas as our output is to be comma separated:
put the dgText of group "text" into tData replace tab with comma in tData
Save the data to file
Now we just need to save out titles and data to file:
put tColumnTitles & return & tData into URL ("file:" & tFileName)