c#でexcelを生成するプログラムを作っています。
サイトを参考に以下のようなプログラムを書きました。
createexcelを1回実行するだけならエラーは出ないのですが、400ファイルとか連続でcreateexcelを呼び出すと「DisconnectedContextが検出されました。」とエラーが出ます。
catchできません。
エラーの出る箇所はフォーカスが当たるので、finallyに入ってからだと思います。
http://www.port135.com/2012/08/18/resolution-for-disconnectedcontext-was-detected-error-when-releasing-excel-object-in-c/
http://hiro-syumi.ldblog.jp/archives/36511362.html
上記を試しましたが、エラーは解消できませんでした。
VB.NetであればDoEventsで解消できるとか書いてありましたが、C#でいうとApplication.DoEventsでエラーが多いと言われているので適用していません。
エラーを解消する方法はないのでしょうか?
C#
1 private void CreateExcel(string filename) 2 { 3 // Excel操作用オブジェクト 4 Microsoft.Office.Interop.Excel.Application xlApp = null; 5 Microsoft.Office.Interop.Excel.Workbooks xlBooks = null; 6 Microsoft.Office.Interop.Excel.Workbook xlBook = null; 7 Microsoft.Office.Interop.Excel.Sheets xlSheets = null; 8 Microsoft.Office.Interop.Excel.Worksheet xlSheet = null; 9 10 try 11 { 12 // Excelアプリケーション生成 13 xlApp = new Microsoft.Office.Interop.Excel.Application(); 14 15 // ◆新規のExcelブックを開く◆ 16 // Addメソッド 17 xlBooks = xlApp.Workbooks; 18 xlBook = xlBooks.Add(); 19 20 // シートを選択する 21 xlSheets = xlBook.Worksheets; 22 xlSheet = xlSheets[1] as Microsoft.Office.Interop.Excel.Worksheet; // 1シート目を操作対象に設定する 23 24 // 表示 25 xlApp.Visible = false; 26 // 警告無視設定 27 xlApp.DisplayAlerts = false; 28 29 // 値を「A1」に代入 30 xlSheet.Range["A1"].Value = "文字列を入力"; 31 32 // 保存 33 xlBook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 34 Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, 35 Type.Missing, Type.Missing, Type.Missing, Type.Missing); 36 37 // 閉じる 38 xlBook.Close(Type.Missing, Type.Missing, Type.Missing); 39 40 } 41 catch (Exception ex) 42 { 43 string s = ex.Message; 44 } 45 finally 46 { 47 if (null != xlApp) 48 { 49 // アプリケーションの終了 50 xlApp.Quit(); 51 52 // アプリケーションのオブジェクトの解放 53 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet); 54 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets); 55 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook); 56 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks); 57 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); 58 59 xlSheet = null; 60 xlSheets = null; 61 xlBook = null; 62 xlBooks = null; 63 xlApp = null; 64 } 65 } 66 }

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/25 03:36
2018/09/25 10:46