convert excel to csv-folder action

Hello all,
I have a problem with my script and i just can’t seem to find the answer. Currently trying to convert many files from .xls to csv and would like to set this up as a folder action. Saying that i can also run it through cron and set to repeat at whatever time I see fit. But the only way I can get this to work is to set the “prompt for” folder up (but that needs to be done manually. So, here is what works:

set theFolder to choose folder with prompt “Choose the folder that contains your Excel files”
tell application “Finder” to set theFiles to (files of theFolder)
set fileCount to count theFiles
repeat with i from 1 to fileCount
set fName to text 1 thru -5 of ((name of item i of theFiles) as text)
if ((name of item i of theFiles) as text) ends with “.xls” then
set tName to (theFolder as text) & fName & “.csv”
tell application “Microsoft Excel”
activate
open (item i of theFiles) as text
save fName in tName as CSV
close active workbook without saving
end tell
end if
end repeat

AND, here is what does not work:

set theFolder to “Users/somefolder/somefolder”
tell application “Finder” to set theFiles to (files of theFolder)
set fileCount to count theFiles
repeat with i from 1 to fileCount
set fName to text 1 thru -5 of ((name of item i of theFiles) as text)
if ((name of item i of theFiles) as text) ends with “.xls” then
set tName to (theFolder as text) & fName & “.csv”
tell application “Microsoft Excel”
activate
open (item i of theFiles) as text
save fName in tName as CSV
close active workbook without saving
end tell
end if
end repeat

Thanks,
tringo

Hi tringo,

two problems:
¢ AppleScript expects colon separated paths starting with the disk name
¢ if a path is defined as a string, the keyword folder is required to specify a folder in a Finder tell block

set theFolder to "Mac HD:Users:somefolder:somefolder:"
tell application "Finder" to set theFiles to (files of folder theFolder)
.

Note: name is always (Unicode) text, so a coercion is useless

ok, that makes sense, but to add it as a folder action i need to add the “upon adding files to this folder” statement?

Hi,

the problem with a folder action is, it’s not recommended to rename or resave a file in the same folder,
because the folder action will be triggered again. But in this case we have a file extension filter, so it should work


on adding folder items to this_folder after receiving theFiles
	repeat with oneFile in theFiles
		set {name:Nm, name extension:Ex} to info for oneFile
		if Ex is "xls" then
			set fName to text 1 thru -5 of Nm
			set tName to (this_folder as text) & fName & ".csv"
			tell application "Microsoft Excel"
				open oneFile as alias
				save fName in tName as CSV
				close active workbook without saving
			end tell
		end if
	end repeat
end adding folder items to

Thanks, Stefan. That worked perfectly!!