我使用此代码从数据集中创建excell:
SQL = "select Bar,Store,Serial from Counter";
dsView = new DataSet();
adp = new OleDbDataAdapter(SQL, Conn);
adp.Fill(dsView, "Counter");
adp.Dispose();
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = false ;
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
int i = 1;
foreach (DataRow comp in dsView.Tables[0].Rows)
{
ws.Cells[i, 1] = comp[0].ToString();
ws.Cells[i, 2] = comp[1].ToString();
ws.Cells[i, 3] = comp[2].ToString();
i++;
}
我有2个问题
如何打开新工作表以及如何关闭此流程
(我看到Excell allwais在后台运行)
答案 0 :(得分:3)
如何打开新表?
您可以使用Workbook.Worksheets.Add
方法添加新工作表。
var newWorksheet =
(Worksheet)xla.Worksheets.Add(Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing);
如何关闭此流程?
您必须关闭工作簿并处理应用程序实例。
SQL = "select Bar,Store,Serial from Counter";
dsView = new DataSet();
using (adp = new OleDbDataAdapter(SQL, Conn))
using (Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application()) {
adp.Fill(dsView, "Counter");
xla.Visible = false ;
try {
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
int i = 1;
foreach (DataRow comp in dsView.Tables[0].Rows) {
ws.Cells[i, 1] = comp[0].ToString();
ws.Cells[i, 2] = comp[1].ToString();
ws.Cells[i, 3] = comp[2].ToString();
i++;
}
} finally {
// Notice that the two following lines are totally optional as the use of
// using blocks assure that the used resource will necessarily be disposed
// when getting out of the using blocks scope.
adp.Dispose();
xla.Dispose();
}
}
这里有一些熟悉使用Microsoft.Office.Interop.Excel
COM程序集的链接。