LoginSignup
59
68

More than 3 years have passed since last update.

備忘録:C#からエクセルファイルを出力する

Last updated at Posted at 2015-01-28

C#からエクセルファイルを出力する方法

EXCELの操作って面倒くさいイメージがあって避けてきたけれど、Pythonで作ったツールをC#で焼き直しすることになり、いろいろ嵌ったので備忘録にとっておく。

  • 今回の環境

Visual Studio 2010

  • 参照の追加

 .NETのMicrosoft.Office.Interop.Excel

Excel操作のコンポーネントは.netとcomにあるが、comはマシンにインストールされているofficeのバージョンに依存するため注意。

  • Usingの宣言
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
  • エクセル出力のメソッド

private void excel_OutPutEx()
{
  //Excelオブジェクトの初期化
  Excel.Application ExcelApp = null;
  Excel.Workbooks wbs = null;
  Excel.Workbook wb = null;
  Excel.Sheets shs = null;
  Excel.Worksheet ws = null;

  try
  {
    //Excelシートのインスタンスを作る
    ExcelApp = new Excel.Application();
    wbs = ExcelApp.Workbooks;
    wb = wbs.Add();

    shs = wb.Sheets;
    ws = shs[1];
    ws.Select(Type.Missing);

    ExcelApp.Visible = false;

    // エクセルファイルにデータをセットする
    for ( int i = 1; i < 10; i++ )
    {
      // Excelのcell指定
      Excel.Range w_rgn = ws.Cells;
      Excel.Range rgn = w_rgn[i, 1];

      try
      {
        // Excelにデータをセット
        rgn.Value2 = "hoge";
      }
      finally
      {
        // Excelのオブジェクトはループごとに開放する
        Marshal.ReleaseComObject(w_rgn);
        Marshal.ReleaseComObject(rgn);
        w_rgn = null;
        rgn = null;
      }
    }

    //excelファイルの保存
    wb.SaveAs(@"HOGE:\huge\sample.xlsx");
    wb.Close(false);
    ExcelApp.Quit();
  }
  finally
  {
     //Excelのオブジェクトを開放し忘れているとプロセスが落ちないため注意
     Marshal.ReleaseComObject(ws);
     Marshal.ReleaseComObject(shs);
     Marshal.ReleaseComObject(wb);
     Marshal.ReleaseComObject(wbs);
     Marshal.ReleaseComObject(ExcelApp);
     ws = null;
     shs = null;
     wb = null;
     wbs = null;
     ExcelApp = null;

     GC.Collect();
  }
}

開放忘れがあるとExcelのプロセスがガベージコレクションが実行されるまで残るので、注意です。自分はこれで半日くらい悩みました。

EXCELを操作するならVBAが圧倒的に楽だけど。。。C#が使いたかったんだ!

59
68
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
68