.NETプログラミング

ExcelのVBA

PythonでExcel制御

参考ページ

Excel出力サンプル

 public class OutputExcel : Output 
 {
   public String m_path = "";
   Application oXL = null;
   Workbooks oWBs = null;
   _Workbook oWB = null;
   Sheets oWSs = null;
   _Worksheet oSheet = null;
   int CurRow = 1;
 
   public override int Open() 
   {
     oXL = new Application();
     oXL.Visible = false;
     oWBs = oXL.Workbooks;
     oWB = oWBs.Add(Type.Missing);
     oWSs = oWB.Worksheets;
     oSheet = (_Worksheet)oWB.ActiveSheet;
     oXL.ScreenUpdating = false; // 画面更新をしない(最初から隠してるけど)
 
     return rc;
   }
 
   public override int Write( OutRow r ) // OutRowはArrayListから派生
   {
     for( int i = 0; i < r.Count; i++ ) 
     {
       Cell c = (Cell)r[i]; // Cellは独自定義。一つのセルに入れる情報
       String s = c.GetValue();
       oSheet.Cells[CurRow,i+1] = s;
     }
     CurRow++; // 行数カウント
 
     // 列幅の最適化
     Range oRng = oSheet.get_Range( "A1", "Z256");
     oRng.EntireColumn.AutoFit();
     ReleaseCom(oRng);
     oRng = null;
 
     return 0;
   }
 
   public override int Close() 
   {
     oXL.ScreenUpdating = true;
     ReleaseCom(oSheet);
     oSheet = null;
     ReleaseCom(oWSs );
     oWSs = null;
     oXL.DisplayAlerts = false; // 「上書きしてもいいですか?」の問い合わせを抑制
     oWB.SaveAs(m_path,Type.Missing,
           Type.Missing,Type.Missing,
           Type.Missing,Type.Missing,XlSaveAsAccessMode.xlExclusive,
           Type.Missing,Type.Missing,Type.Missing,Type.Missing );
     oWB.Close(false,Type.Missing, Type.Missing);
     ReleaseCom(oWB);
     oWB = null;
     ReleaseCom(oWBs);
     oWBs = null;
     oXL.Quit();
     ReleaseCom(oXL);
     oXL = null;
     
     GC.Collect();		//ガーベジコレクト起動
     return 0;
   }
 
   void ReleaseCom(Object o) 
   {
     System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
   }
 }

WorkSheetなどの特定範囲を参照する

VBAからの翻訳のコツ

遅延バインディング

Excelのプロセスが残る問題

※ここに書いたことは2006年頃の状況なので、最近のバージョンであれば改善されているかもしれない。

枠線を引く

1行目をタイトル行として背景色をつける

Excelのワークシート名に使えない記号の処理


トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2022-10-14 (金) 14:09:04