Export dataset to CSV and send as email attachment

Hi Good day!
I just want to ask some idea from you guys. is it possible to export dataset to CSV file without saving to a file directory? what i want to do after exporting the dataset is automatically send as file attachment in email?

Instead of using system.dataset.exportCSV use system.dataset.toCSV. Then use system.net.sendEmail to attach the data and send

I don’t think your suggestion will work since sendEmail() requires byte data.

@jmacascas, have a look at this: Email with Excel file Attached without prompting

1 Like

You probably could use system.file.readFileAsBytes after you export the CSV.
EDIT
Another solution would be to use a report if you have the reporting module. Then you can email, FTP, print, and or save the file fairly easy.

Use system.dataset.toCSV(), then use Java’s StandardCharsets.UTF_8.encode(theCSVstring).array() to get the bytes for system.net.sendEMail().

3 Likes

Ive done something similar using:

			csv = system.dataset.toCSV(your dataset here)
			from org.python.core.util import StringUtil
			email = []
			email.append('your@email.com')
			shared.app.email.send(email,'Subject here','Message here', attachmentNames = ['filename.csv'],attachmentData=[StringUtil.toBytes(csv)])

shared.app.email.send is just a script that wraps around system.net.sendEmail

2 Likes

Yet another option:

from java.lang import String
String(system.dataset.toCSV(<dataset>)).getBytes("UTF-8")
2 Likes

Hi Guys, here’s my script.

from datetime import datetime 

myDataset=system.tag.read("[default]Machine/machine1/Stats/Monitoring/TimeRecord").value
hostName = system.tag.read("[default]Machine/machine1/Hostname").value

#Iterate the dataset
for row in range(myDataset.getRowCount()):
	for col in range(myDataset.getColumnCount()):
		myDataset.getValueAt(row, col) 


excelstr = system.dataset.dataSetToExcel(1,[myDataset])
excelbytes = excelstr.encode("UTF8")
filename = hostName +"_"+(datetime.today().strftime("%m-%d-%y - %H %M %S"))+ ".xls"


body = "<HTML><BODY><H1>Test101</H1>"
#body += "This is a system generate email <font color='black'>black</font></BODY></HTML>"
recipients = ["jmacascas@email.com"]
cc_recipients = [""]
smtp_server = "default"
subject = "Here is the file you requested"
system.net.sendEmail(smtpProfile=smtp_server, fromAddr="ignition@email.com", subject= subject, body=body, html=0, to=recipients, cc=cc_recipients,[filename],[excelbytes])

but i’m getting this syntax error.
SyntaxError: (‘non-keyword arg after keyword arg’, (’’, 26, 146, ‘system.net.sendEmail(smtpProfile=smtp_server, fromAddr="ignition@email.com", subject= subject, body=body, html=0, to=recipients, cc=cc_recipients,[filename],[excelbytes])\n’))

Hi Code_skin,

Thank you for sharing the link. I got some idea and able to solve my problem.
my script is now working using system.dataset.exportExcel

1 Like