在C#excell中出现问题与2表

我使用这个代码从数据集中制作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个问题

如何打开新表以及如何closures这个过程

(我看到Excell allwais在后台运行)

如何打开新表?

您可以使用Workbook.Worksheets.Add方法添加一个新工作表。

 var newWorksheet = (Worksheet)xla.Worksheets.Add(Type.Missing , Type.Missing , Type.Missing , Type.Missing); 

如何closures这个过程?

您必须closures工作簿并处理应用程序实例。

 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程序集的链接。

  1. 如何:向工作簿添加新的工作表 ;
  2. 使用工作表 ;
  3. 使用工作簿 ;
  4. 使用范围 ;
  5. 使用单元格 。