Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
4555
How can we send an Excel sheet as an email attachment (without saving to a file system)
posted

 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
  
 

Web_Excel_Stream.zip
  • 5
    Offline posted

    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