I need to export some information (in a .net datatable form) to excel and then send that information via email. I found this here How to export DataTable to Excel in C#, works great but one of the requirements is not to save the Excel, kind of send the stream not the file itself, any Ideas? because all the examples that I found, all of them, save the Excel file first.
Asked
Active
Viewed 3,676 times
0
-
[`System.Net.Mail.Attachment`](http://msdn.microsoft.com/en-us/library/6sdktyws(v=vs.110).aspx) has a constructor with an `IO.Stream`. – Tim Schmelter Jan 16 '14 at 15:07
-
My problem is not the mail part, is how I create the excel without saving it, create a method to create the excel and return an stream, but don't know how to create an Excel stream with the Office.Interop – ddieppa Jan 16 '14 at 15:10
1 Answers
1
I'm not sure but i think that Office.Interop
cannot do that.
Why don't you use EPPlus
to load the excel from the DataTable
. It has a LoadFromDataTable
method and a Stream
property:
using (var package = new OfficeOpenXml.ExcelPackage())
{
var sheet = package.Workbook.Worksheets.Add("Sheetname");
sheet.Cells["A1"].LoadFromDataTable(tblData, true, OfficeOpenXml.Table.TableStyles.Medium6);
var excelAttachment = new System.Net.Mail.Attachment(package.Stream, "Excelname");
// ...
}
(note that this code is not tested)

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
Well, I was trying not to use another library (following orders) but I will give a shot to [EPPlus](http://epplus.codeplex.com/) and then try to convince the upper level management – ddieppa Jan 16 '14 at 16:02
-
well I ended using EPPlus, thanks @TimSchmelter for the advice, EPPlus has a lot of options for saving or whatever you want to do with the excel file, I used the package.GetAsByteArray(), thanks again – ddieppa Jan 21 '14 at 14:11