Search code examples
macoscsvapplescriptadobe-indesign

Applescript convert variable into a string with commas for CSV


I have a variable that contains {"THIS", "THAT"} that I am trying to write to a csv so that the csv formats as THIS,THAT. Current it just spits out as THISTHAT.

I think I need to repeat though the variable but I am not sure...

the code is as follows (check the ---> for the important bits):

tell application "Adobe InDesign CC 2014"   
delete unused swatches of document 1
set _NotUSED to {"None", "Paper", "Black", "Registration", "Keyline", "ImageLabel", "C=0 M=0 Y=0 K=37", "C=0 M=100 Y=100 K=0", "Map this to white ->", "Dieline", "C=0 M=100 Y=0 K=0"} as string

try
---> Get the variables
    set _UpDatedList to get (name of swatches of document 1 whose name is not in _NotUSED)

on error

    display alert {"Your document has no spot colours"}

end try

end tell

set filePath to (path to desktop as text) & "Pantones.csv"

---> Set the theString to the variables
set theString to _UpDatedList as string

set theResult to writeTo(filePath, theString, text, false)

if not theResult then display dialog "There was an error writing the data!"

on writeTo(targetFile, theData)
try

    set openFile to open for access file targetFile with write permission

---> write the variables to csv
    write theData to openFile
    close access openFile
    return true
    on error
    try
        close access file targetFile
    end try
    return false
end try
end writeTo

Solution

  • Try this, the easiest way to convert a list to CSV is to use text item delimiters.
    The main problem is the coercion to string in the 3rd line. Delete as string.

    tell application "Adobe InDesign CC 2014"
        delete unused swatches of document 1
        set _NotUSED to {"None", "Paper", "Black", "Registration", "Keyline", "ImageLabel", "C=0 M=0 Y=0 K=37", "C=0 M=100 Y=100 K=0", "Map this to white ->", "Dieline", "C=0 M=100 Y=0 K=0"}
        try
            set _UpDatedList to (get name of swatches of document 1 whose name is not in _NotUSED)
        on error
            display alert "Your document has no spot colours" buttons {"Cancel"}
            return -- abort the script
        end try
    end tell
    
    set filePath to (path to desktop as text) & "Pantones.csv"
    
    set {TID, text item delimiters} to {text item delimiters, ","}
    set csvString to _UpDatedList as text
    set text item delimiters to TID
    
    set theResult to writeTo(filePath, csvString)
    
    if not theResult then display dialog "There was an error writing the data!"
    
    on writeTo(targetFile, theData)
        try
            set openFile to open for access file targetFile with write permission
            write theData to openFile
            close access openFile
            return true
        on error
            try
                close access file targetFile
            end try
            return false
        end try
    end writeTo