1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#からExcel操作 テンプレ - ライブラリレス(※要Excel)

Last updated at Posted at 2021-02-01

1. コンパイル用バッチ

※Officeのバージョンに依存しますので、適宜変更してください。

compile.bat

csc ^
 /r:C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll ^
 /r:C:\Windows\assembly\GAC_MSIL\office\15.0.0.0__71e9bce111e9429c\Office.dll ^
 %*

1-1. コンパイル方法

compile.bat ほげほげ.cs

2. 現在開いているExcelファイルのアクティブなシートを操作するテンプレ

・画面更新の停止
・再計算の停止

2-1. ソースコード

※開いているエクセルシートに対して処理を行うので、むやみに実行しないでください


using System;
using System.Runtime.CompilerServices; // to use [MethodImpl(MethodImplOptions.NoInlining)]
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

class ExcelSample
{
    [MethodImpl(MethodImplOptions.NoInlining)] // 最適化抑制
    static void OverwriteActiveSheet()
    {
        Excel.Application oExcelApp = null;
        Excel.Worksheet oSheet = null;
        
        try {
            oExcelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
        }
        catch ( System.Runtime.InteropServices.COMException ) {
            Console.WriteLine("Failed to get Excel.Application.");
            return;
        }
        
        try {
            var oBook = (Excel.Workbook)oExcelApp.ActiveWorkbook;
            if ( oBook != null ) {
                oSheet = (Excel.Worksheet)oBook.ActiveSheet;
            }
        }
        catch ( System.Runtime.InteropServices.COMException ) {
        }
        if ( oSheet == null ) {
            Console.WriteLine("Failed to get ActiveWorkbook or ActiveSheet.");
            return;
        }

        bool screenUpdatingBackup = oExcelApp.ScreenUpdating;
        Excel.XlCalculation calcModeBackup = oExcelApp.Calculation;
        try {
            oExcelApp.ScreenUpdating = false; // 画面更新の停止
            oExcelApp.Calculation = Excel.XlCalculation.xlCalculationManual; // 再計算の停止
            
            // 処理を追加  ここから

            // セルの読み込み
            Excel.Range oCells = oSheet.Cells;
            var oRange = oCells[3, 2] as Excel.Range; // B3セル
            Console.WriteLine(oRange.Value);
            Console.WriteLine(oRange.Value2);
            Console.WriteLine(oRange.Text);

            // セルへの書き込み
            oRange = oCells[4, 3] as Microsoft.Office.Interop.Excel.Range;
            oRange.Value = "hoge";

            // 罫線を引く
            Excel.Borders oBorders;
            Excel.Border oBorder;
            oRange = oSheet.Range[oSheet.Cells[2, 2], oSheet.Cells[4, 4]]; //  select B2 - D4
            oBorders = oRange.Borders;
            oBorder = oBorders[Excel.XlBordersIndex.xlEdgeBottom];// xlEdgeLeft xlEdgeRight xlEdgeTop
            oBorder.LineStyle = Excel.XlLineStyle.xlContinuous;

            // 処理を追加  ここまで
        }
        finally {
            if ( oExcelApp.Calculation != calcModeBackup ) {
                oExcelApp.Calculation = calcModeBackup;
            }
            if ( oExcelApp.ScreenUpdating != screenUpdatingBackup ) {
                oExcelApp.ScreenUpdating = screenUpdatingBackup;
            }
        }
    }

    [STAThread]
    static void Main(string[] args)
    {
        OverwriteActiveSheet();
    }
}

2-2. 入力データ

image.png

2-3. 実行結果


2021/02/03 0:00:00
44230
2月3日

image.png

3. Excelファイルを開く - 参考サイト

4. 罫線を引く - 参考サイト

5. セル結合させる - 参考サイト

要約:Rangeに対してMerge()する

参考サイト

Microsoft.Office.Interop.Excel を使う以外の選択肢

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?