Excel.Application app = new Excel.ApplicationClass();
Excel.Workbook wb = new Excel.WorkbookClass();
Передача данных из dataSet в Excel
Как в Visual Studio .NET 2003 можно реализовать передачу данных из dataSet в документ Excel?
подключить Exсel как таблицу БД и вперед
Я пробовала так:
Add reference->COM->Excel 11.0
Потом
Код:
На последней строке выскакивает ошибка (
Вот как можно это сделать:
1). Project->Add reference->COM->Excel 11.0
2). Код
Код:
Excel.Application app = null;
Excel.Workbooks wbs = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
try
{
app = new Excel.ApplicationClass();
app.Visible = true;
wbs = (Excel.Workbooks)(app.GetType().InvokeMember("Workbooks",BindingFlags.GetProperty, null, app, null));
wb = (Excel.Workbook)(wbs.GetType().InvokeMember("Add",BindingFlags.InvokeMethod, null, wbs, null));
ws = (Excel.Worksheet)wb.ActiveSheet;
Excel.Range range = null;
for(int i=0; i<this.dataSet2.Tables[0].Rows.Count;i++)
for(int j=0;j<this.dataSet2.Tables[0].Columns.Count;j++)
{
range = (Excel.Range)ws.Cells[i+1,j+1];
range.Value2 = this.dataSet2.Tables[0].Rows.ItemArray.GetValue(j).ToString();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
}
finally
{
if (ws != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
if (wb != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
if (app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
Excel.Workbooks wbs = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
try
{
app = new Excel.ApplicationClass();
app.Visible = true;
wbs = (Excel.Workbooks)(app.GetType().InvokeMember("Workbooks",BindingFlags.GetProperty, null, app, null));
wb = (Excel.Workbook)(wbs.GetType().InvokeMember("Add",BindingFlags.InvokeMethod, null, wbs, null));
ws = (Excel.Worksheet)wb.ActiveSheet;
Excel.Range range = null;
for(int i=0; i<this.dataSet2.Tables[0].Rows.Count;i++)
for(int j=0;j<this.dataSet2.Tables[0].Columns.Count;j++)
{
range = (Excel.Range)ws.Cells[i+1,j+1];
range.Value2 = this.dataSet2.Tables[0].Rows.ItemArray.GetValue(j).ToString();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
}
finally
{
if (ws != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
if (wb != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
if (app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}