0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#でExcelファイルを作る

Posted at

C#でExcelファイルを作る

業務でExcel出力を実装する機会がありそうなので、先に試しておこうと思って調べた。
C#からExcelファイルを作る記事は結構あったので、2シート出力してみた。

環境

  • VisualStudio2022
  • .NET Framework4.7.2
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace ExcelSample
{
	  class ExcelControl
    {
        // 2シートのExcelを新規作成する
        public void CreateExcel()
        {
            Excel.Application excelApp = default;
            Excel.Workbooks workbooks = default;
            Excel.Workbook workbook = default;


            try
            {
                excelApp = new Excel.Application();
                workbooks = excelApp.Workbooks;
                workbook = workbooks.Add();

                // MEMO:1つ目のシートは自動で作られる
                workbook.Sheets[1].Select(Type.Missing);

                // 1シート目
                Excel.Range range = workbook.Sheets[1].Cells;
                Excel.Range cell = range[1, 1];
                try
                {
                    cell.Value2 = "テスト1";
                }
                finally
                {
                    Marshal.ReleaseComObject(range);
                    Marshal.ReleaseComObject(cell);
                }

                // 2シート目
                workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);
                Excel.Range range2 = workbook.Sheets[2].Cells;
                Excel.Range cell2 = range2[1, 1];
                try
                {
                    cell2.Value2 = "テスト2";
                }
                finally
                {
                    Marshal.ReleaseComObject(range2);
                    Marshal.ReleaseComObject(cell2);
                }

                // ファイルの保存
                workbook.SaveAs(@"D:ExcelSampleOutput\sample.xlsx");
                workbook.Close();
                excelApp.Quit();
            }
            finally
            {
				// 必ず解放する
                Marshal.ReleaseComObject(workbook);
                Marshal.ReleaseComObject(workbooks);
                Marshal.ReleaseComObject(excelApp);
            }
        }
    }
}

思ったよりも簡潔に書けそうだけど、プロパティも多くあったので調べておいた方がいいのかなぁ。
オブジェクトの解放は忘れずに!

参考

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?