To put data into excel sheets, you don't need to bring the data into datasets. You can directly pull the data onto excel sheet in many ways. One of this ways is to use QueryTables.Add method. With this approach, when data is modified on source, change is reflected in the excel file. ie: (using sample Northwind data):
void Main()
{
Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
var workbook = xl.Workbooks.Add();
Worksheet sht1, sht2;
sht1 = ((Worksheet)workbook.Sheets[1]);
if (workbook.Sheets.Count < 2)
{
sht2 = (Worksheet)workbook.Sheets.Add();
}
else
{
sht2 = ((Worksheet)workbook.Sheets[2]);
}
xl.Visible = true;
sht1.Move(sht2);
sht1.Name = "Data Sheet 1";
sht2.Name = "Data Sheet 2";
string strCon = @"OLEDB;Provider=SQLNCLI11.0;server=.\SQLExpress;Trusted_Connection=yes;Database=Northwind";
Range target1 = (Range)sht1.Range["A1"];
sht1.QueryTables.Add(strCon, target1, "Select * from Customers" ).Refresh();
Range target2 = (Range)sht2.Range["A1"];
sht2.QueryTables.Add(strCon, target2, "Select * from Orders").Refresh();
}
Another option is to use the Epplus library from Nuget. Using that one you can simply have many sheets where you load the content from collections. ie:
void Main()
{
ExcelPackage pck = new ExcelPackage();
var collection1 = from c in db.Customers
select new
{
CustomerName = c.CompanyName,
ContactPerson = c.ContactName,
FirstOrder = c.Orders.Min(o => o.OrderDate),
LastOrder = c.Orders.Max(o => o.OrderDate),
OrderTotal = c.Orders.Any() ? c.Orders.Sum(o => o.OrderDetails.Sum(od => od.Quantity * od.UnitPrice)) : 0M,
Orders = c.Orders.Count()
};
var collection2 = db.Orders.Select(o => new {
OrderId = o.OrderID, Customer=o.CustomerID, OrderDate=o.OrderDate});
var ws1 = pck.Workbook.Worksheets.Add("My Sheet 1");
//Load the collection1 starting from cell A1 in ws1
ws1.Cells["A1"].LoadFromCollection(collection1, true, TableStyles.Medium9);
ws1.Cells[2, 3, collection1.Count() + 1, 3].Style.Numberformat.Format = "MMM dd, yyyy";
ws1.Cells[2, 4, collection1.Count() + 1, 4].Style.Numberformat.Format = "MMM dd, yyyy";
ws1.Cells[2, 5, collection1.Count() + 1, 5].Style.Numberformat.Format = "$#,##0.0000";
ws1.Cells[ws1.Dimension.Address].AutoFitColumns();
var ws2 = pck.Workbook.Worksheets.Add("My Sheet 2");
//Load the collection1 starting from cell A1 in ws1
ws2.Cells["A1"].LoadFromCollection(collection2, true, TableStyles.Medium9);
//...and save
var fi = new FileInfo(@"d:\temp\AnonymousCollection.xlsx");
if (fi.Exists)
{
fi.Delete();
}
pck.SaveAs(fi);
}
PS: Both QueryTables and Epplus approaches are fast. If you would anyway use datasets and\or setting cell values in a loop, then be sure you have small data.