2010-12-06 4 views
1

私はデータセットからエクセルを作るためにこのコードを使用して問題を抱えて:エクセルは2枚

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問題

新しいシートを開くには、どのようにして、このプロセスを閉じる方法

(私はエクセルallwaisがバックグラウンドで実行されていることを参照)

答えて

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アセンブリでの作業に慣れるためのいくつかのリンクが。

  1. How to: Add New Worksheets to Workbooks;
  2. Working with Worksheets;
  3. Working with Workbooks;
  4. Working with Ranges;
  5. Working with Cells
関連する問題