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
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.
local tFileName, tFileContents
ask file "Please choose a where you want to save the file" with type "Comma Separated
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
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
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)