擅长C#-2张纸有问题

擅长C#-2张纸有问题,c#,excel,C#,Excel,我使用以下代码从数据集生成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.Ex

我使用以下代码从数据集生成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++;
        }
我有两个问题

如何打开新工作表以及如何关闭此流程

(我看到ExcellAllwais在后台运行)

如何打开新工作表?

您可以使用
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程序集

  • )
  • )
  • )
  • )