tags:

views:

675

answers:

4

I have C# code that sends an email. In the body of the email i want to send contents of an excel sheet.

One way to do this is create html table with html rows for every record in the excel file and embed this html code in the body of the email.

Is there any simpler way to do this? Something where i can just specify the path of the excel sheet and directly the table would be copied in the email body?

Thanks.

A: 

You could try doing this via a ADODB connection to the excel sheet. http://support.microsoft.com/kb/306023

  1. Open a recordset to the Excel sheet
  2. Call recordset.GetString (http://www.devguru.com/technologies/ado/quickref/recordset_getstring.html). This will dump the contents of the sheet into the string.

This may be shorter (length-wise) then the code you had planned, which probably involved Excel automation.

Jamie
A: 

it's not embedded, but you can try the attachment class : http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

alternatives are to use a 3rd party excel control to open it, copy the data out, and paste it into the message.

Stephen Wrighton
A: 

I assume you want to do this natively in c#.

I think your best bet is to use Office Automation in C# to save the spreadsheet to an HTML file format. You can then open this file with a StreamReader object and embed the text into the body of your message.

Microsoft has an article on automating Excel, with some code samples to get you started:

How to automate Microsoft Excel from Microsoft Visual C# .NET http://support.microsoft.com/kb/302084

Robert Harvey
+1  A: 

By far the easiest is to use the Workbook.SendMail() method.

Example code:

Excel.Workbook myWorkbook = xlApp.Workbooks["Book1.xls"];

string recipients = "[email protected]";
string subject = "Proposal for Review";
bool returnReceipt = false;

myWorkbook.SendMail(recipients, subject, returnReceipt);

Note that the recipients parameter is actually typed as System.Object so that the argument passed in can be a string[] if you have multiple recipients.

Sources:

(1) http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.sendmail(VS.80).aspx

(2) http://msdn.microsoft.com/en-us/library/bb178034.aspx

You also might want to have a look at Ron de Bruin's Sending mail from Excel with CDO approach, but the Workbook.SendMail() method really is the easiest.

Hope this helps...

Mike

Mike Rosenblum