How can we send an Excel sheet as an email attachment (without saving to a file system)
New DiscussionThis article covers how to make an Excel Workbook that
contains a worksheet, fill the WorkSheet with the contents of one
Wingrid and finally Export the WorkBook as an email attachement without
writing it to a disk:
The steps are as follows:
1) We need to Instantiate a workbook object:
WorkBook wbk = new
WorkBook();
2) Set the ExportMode of the Exporter to Custom:
UltraWebGridExcelExporter1.ExportMode =
Infragistics.WebUI.UltraWebGrid.ExcelExport.ExportMode.Custom;
3) Add a Worksheet to
the Workbook:
wbk.Worksheets.Add(“Grid
One”);
4) Use the Export Method of the Exporter to Export the
UltraGrid to the Worksheet:
this.UltraWebGridExcelExporter1.Export(this.UltraWebGrid1,
wbk);
5) Populate an Excel object in memory; the Excel object is
then persisted as an output stream:
MemoryStream
stream = new MemoryStream();
6) Write the workbook “wbk” into our newly created
stream
wbk.Save(stream);
7) Create a Byte[ to contain the stream:
Byte[ bytearray =
(Byte[)Array.CreateInstance(typeof(byte),stream.Length);
8) Read the stream into the Byte[:
stream.Read
(bytearray, 0, (int)stream.Length);
9) Create a new Stream
MemoryStream ms = new MemoryStream(bytearray);
10) Create an email object
System.Net.Mail.MailMessage objMail = new System.Net.Mail.MailMessage();
System.Net.Mail.Attachment objAtt = new System.Net.Mail.Attachment(ms,
“TextFile.xls”);
objMail.From = new MailAddress(“MFahim@Infragistics.com”);
objMail.To.Add(new MailAddress(“MFahim@Infragistics.com”));
objMail.Subject = “Exported Excel”;
objMail.Body = “Exported Excel”;
objMail.Attachments.Add(objAtt);
SmtpClient c = new SmtpClient();
c.Host = “localhost”;
c.Port = 25;
c.UseDefaultCredentials = true;
c.Send(objMail);
stream.Close(); // Close the stream