Skip to content

Infragistics Community Forum / Cross Platform / Ultimate UI for Xamarin / How can we send an Excel sheet as an email attachment (without saving to a file system)

How can we send an Excel sheet as an email attachment (without saving to a file system)

New Discussion
[Infragistics] Magued Fahim
[Infragistics] Magued Fahim asked on Sep 25, 2013 11:47 PM

This 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

Sign In to post a reply

Replies

  • 0
    Greg Duncan
    Greg Duncan answered on Sep 25, 2013 11:47 PM

    One important thing to note, Before #8 make sure make sure you set the first stream to position = 0. This is clear in the attached code, but not in the text above… If you don't your attachment will be sized right, but empty.

    stream.Position = 0; // Star the stream at position 0

     

  • You must be logged in to reply to this topic.
Discussion created by
Favorites
Replies
Created On
Last Post
Discussion created by
[Infragistics] Magued Fahim
Favorites
0
Replies
1
Created On
Sep 25, 2013
Last Post
12 years, 11 months ago

Suggested Discussions

Created on

Sep 25, 2013 11:47 PM

Last activity on

Feb 23, 2026 6:34 AM