プログラミングのメモ

プログラミングの学び直し備忘録

C#:Excel

確認中

確認中

C#:Excel(COM)

参考

参考

Excelファイルを C#VB.NET で読み込む "正しい" 方法

Excelファイルを C# と VB.NET で読み込む "正しい" 方法

Interop.ExcelExcelプロセス絶対殺すコード

【Interop.Excel】Excelプロセス絶対殺すコード

ExcelDataReader で XLS と XLSX の両方を読込む方法

ExcelDataReader で XLS と XLSX の両方を読込む方法

C#Excelを読み込んで操作する方法を公開|C# Excel操作テクニック.NET

C#でExcelを読み込んで操作する方法を公開|C# Excel操作テクニック.NET

【開いているBOOK確認】

VB.NET 開いているExcelBookとSheetをチェック - Take it easy!

Imports Excel = Microsoft.Office.Interop.Excel

''' <summary>
''' 
''' </summary>
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Debug.Print(fExcelOpen("BOOK1"))

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="ExFileName"></param>
    ''' <returns></returns>
    Private Function fExcelOpen(ByVal ExFileName As String) As Boolean
        Dim oExcel As Excel.Application
        Dim oBooks As Excel.Workbooks
        Dim oBook As Excel.Workbook
        Dim fsts As Boolean =FalseDim oSheets As Excel.Sheets
        Dim oSheet As Excel.Worksheet
        Try
            '別プロセスのExcelを取得する
            'GetObjext第1引数のファイルパスは省略する
            oExcel = GetObject(, “Excel.Application”)
            '開いているブックを全て取得する
            oBooks = oExcel.Workbooks

            'ブック毎に確認
            For Each oBook In oBooks
                Debug.Print(oBook.Name)
                If oBook.Name = ExFileName Then
                    fsts = True
                End If
            Next
            'For Each oBook In oBooks
            '    Debug.Print(oBook.Name)
            'Next

        Catch ex As Exception
            MessageBox.Show(ex.Message)

        Finally
            'COMコンポーネントの解放
            If Not oSheet Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet)
                oSheet = Nothing
            End If
            If Not oSheets Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheets)
                oSheets = Nothing
            End If
            'COMコンポーネントの解放
            If Not oBook Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
                oBook = Nothing
            End If
            If Not oBooks Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks)
                oBooks = Nothing
            End If
            If Not oExcel Is Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
                oExcel = Nothing
            End If
        End Try

        Return fsts

    End Function

End Class

【C#】サンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 参照設定
// Microsoft Excel 16.0 Object Library

using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 
/// </summary>
namespace Excel_COM_2.ExcelCOM_01
{
    /// <summary>
    /// 
    /// </summary>
    class clsExcelCOM_01
    {
        /// <summary>
        /// 
        /// </summary>
        public static void mth_Main()
        {
            var app = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Excel.Workbooks wbs = app.Workbooks;
                try
                {
                    string sFile_fp = @"D:\COM_TEST.xlsx";
                    Excel.Workbook wb = wbs.Open(sFile_fp);
                    try
                    {
                        Excel.Sheets wss = wb.Sheets;
                        try
                        {
                            //Worksheet ws = wss[1];
                            Excel.Worksheet ws = wss["シート(No2)"];
                            try
                            {
                                //================================
                                // 最終行/最終列
                                //================================
                                int lastRow_0 = ws.Cells[ws.Rows.Count, 1].End[Excel.XlDirection.xlUp].Row;
                                int lastCol_0 = ws.Cells[1, ws.Columns.Count].End[Excel.XlDirection.xlToLeft].Row;

                                //===============================================
                                // 使用範囲を一括で二次元配列にコピー
                                //===============================================
                                Object[,] rangeArray;
                                Excel.Range rng = ws.UsedRange;
                                try
                                {
                                    rangeArray = rng.Value;
                                }
                                finally { Marshal.ReleaseComObject(rng); }

                                


                                // 二次元配列に対してループを回す
                                int lastRow = rangeArray.GetLength(0);
                                int lastCol = rangeArray.GetLength(1);
                                for (int r = 1; r <= lastRow; r++)
                                {
                                    //Console.WriteLine(r);
                                    for (int c = 1; c <= lastCol; c++)
                                    {
                                        Console.WriteLine(rangeArray[r, c]);
                                    }
                                }
                            }
                            finally { Marshal.ReleaseComObject(ws); }
                        }
                        finally { Marshal.ReleaseComObject(wss); }
                    }
                    finally
                    {
                        if (wb != null)
                        {
                            wb.Close(false);
                        }
                        Marshal.ReleaseComObject(wb);
                    }
                }
                finally { Marshal.ReleaseComObject(wbs); }
            }
            finally
            {
                if (app != null)
                {
                    app.Quit();
                }
                Marshal.ReleaseComObject(app);
            }
        }


    }
}

【C#】サンプル2 (開いているブック、シートリスト、処理[書込み、読込み、検索、塗りつぶし])

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Runtime.InteropServices;
// [COM]
using Excel = Microsoft.Office.Interop.Excel;

namespace Excel_COM_10
{
    public partial class Form1 : Form
    {

        Excel.Application xlApp;

        Excel.Workbooks xlBooks;
        Excel.Workbook xlBook;

        Excel.Sheets xlSheets;
        //Excel.Worksheets xlApp;
        Excel.Worksheet xlWSheet;

        Excel.Range xlRng;

        //######################################################
        /// <summary>
        /// コンストラクタ
        /// </summary>
        //######################################################
        public Form1()
        {
            InitializeComponent();
        }

        //**************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //**************************************************************
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        //**************************************************************
        /// <summary>
        /// 開いているBOOK
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //**************************************************************
        private void cmd_開いているブック_Click(object sender, EventArgs e)
        {

            //=========================================
            //## バックグラウンドプロセス #####
            //=========================================
            foreach (var p in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
            {
                if (p.MainWindowTitle == "")
                {
                    p.Kill();
                }
            }

            //=========================================
            //## Excel起動確認 ######
            //=========================================
            try
            {
                xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Excelが起動されていません。\n\r" + ex.Message);
                return;
            }

            //=========================================
            //## 開いているExcelのBookを取得 ######
            //=========================================
            // <MEMO>
            // Excel操作ソフトを実行中に強制終了などするとCOMオブジェクトの解放モレが発生し、
            // プロセスが残る状態になる。その状態で再度Excel操作をしようとすると、残った
            // プロセスの方を操作対象としてしまう。結果、新しいブックを開いていても以下の操作に
            // 失敗することがある。この場合、タスクマネージャーからEXCEL.EXEプロセスをキルする必要がある
            xlBooks = xlApp.Workbooks;
            if (xlBooks.Count==0)
            {
                MessageBox.Show("プロセスが残っていないか確認してください。");
                return;
            }

            // ## Book ##################
            StringBuilder sb = new StringBuilder();

            // == foreach ===============
            this.cbo_開いているブック.Text = "";
            this.cbo_開いているブック.Items.Clear();
            foreach (Excel.Workbook item in xlBooks)
            {
                this.cbo_開いているブック.Items.Add(item.Name);
                sb.Append(item.Name + "\n\r");
            }
            this.cbo_開いているブック.SelectedIndex = 0;
            MessageBox.Show(sb.ToString());

            // == Books.Count =============
            sb.Clear();
            for (int i = 0; i < xlBooks.Count; i++)
            {
                sb.Append(xlBooks.get_Item(i+1).Name + "\n\r");
            }
            MessageBox.Show(sb.ToString());


        }

        //**************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //**************************************************************
        private void cmd_シートリスト_Click(object sender, EventArgs e)
        {
            //## バックグラウンドプロセス Kill #####
            (new catProcess.clsProcess()).Mth_BackgroundKill("EXCEL");

            //=========================================
            //## Excel起動確認 ######
            //=========================================
            try
            {
                xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Excelが起動されていません。\n\r" + ex.Message);
                return;
            }

            //## ブックオブジェクト/シートコレクション #####
            xlBook = xlBooks[this.cbo_開いているブック.Text];
            xlSheets = xlBook.Worksheets;

            // ## Sheets ##################
            StringBuilder sb = new StringBuilder();

            // == foreach ===============
            this.cbo_シートリスト.Text = "";
            this.cbo_シートリスト.Items.Clear();
            foreach (Excel.Worksheet item in xlSheets)
            {
                this.cbo_シートリスト.Items.Add(item.Name);
                sb.Append(item.Name + "\n\r");
            }
            this.cbo_シートリスト.SelectedIndex = 0;
            MessageBox.Show(sb.ToString());

        }

        //**************************************************************
        /// <summary>
        /// 処理(書込み、読込み、検索、塗潰し)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //**************************************************************
        private void cmd_処理01_Click(object sender, EventArgs e)
        {
            //## バックグラウンドプロセス Kill #####
            (new catProcess.clsProcess()).Mth_BackgroundKill("EXCEL");

            //## ブックオブジェクト/シートオブジェクト #####
            xlBook = xlBooks[this.cbo_開いているブック.Text];
            xlWSheet = xlBook.Worksheets[this.cbo_シートリスト.Text];


            //=========================================
            //##  ######
            //=========================================
            xlWSheet.Cells.Clear();
            for (int i = 0; i < 10; i++)
            {
                xlWSheet.Cells[i + 1, i + 1].value = i;
            }

            xlWSheet.Cells[1, 3].value = "TEST";
            xlWSheet.Cells[2, 2].value = "TEST";
            xlWSheet.Cells[5, 1].value = "TEST";

            var s = xlWSheet.Cells[1, 1].value;

            //=========================================
            //##  ######
            //=========================================
            Excel.Range rngFindCell;
            rngFindCell = xlWSheet.Cells.Find(
                                              What: "TEST",
                                              LookIn: Excel.XlFindLookIn.xlValues,
                                              LookAt: Excel.XlLookAt.xlWhole,
                                              MatchCase: false,
                                              MatchByte: false,
                                              SearchFormat: false
                                              );

            if (rngFindCell == null)
            {
                MessageBox.Show("Nothing");
                return;
            }

            Excel.Range rngFind_1st = rngFindCell;
            Excel.Range rngFind_List = rngFindCell;

            do
            {
                rngFindCell = xlWSheet.Cells.FindNext(rngFindCell);
                if (rngFindCell == null) break;
                if (rngFindCell.Address == rngFind_1st.Address) break;

                //xlWSheet.Activate();
                rngFind_List = xlApp.Union(rngFind_List, rngFindCell);

            } while (true);

            foreach (Excel.Range item in rngFind_List)
            {
                Console.WriteLine(item.Address);
            }

            rngFind_List.Interior.Color = Color.FromArgb(255, 255, 0);
            MessageBox.Show("Fin.");
        }

        //**************************************************************
        /// <summary>
        /// R1C1参照形式
        ///     [Excel]-[オプション]-[数式]-[数式の処理]
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //**************************************************************
        private void cmd_参照形式_Click(object sender, EventArgs e)
        {
            //## バックグラウンドプロセス Kill #####
            (new catProcess.clsProcess()).Mth_BackgroundKill("EXCEL");

            //=========================================
            //## Excel起動確認 ######
            //=========================================
            try
            {
                xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Excelが起動されていません。\n\r" + ex.Message);
                return;
            }

            //## R1C1参照形式 #####
            try
            {
                xlApp.ReferenceStyle = (xlApp.ReferenceStyle == Excel.XlReferenceStyle.xlA1) ?
                                                                Excel.XlReferenceStyle.xlR1C1 :
                                                                Excel.XlReferenceStyle.xlA1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //throw;
                return;
            }

        }
    }
}

プロセス

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Excel_COM_10.catProcess
{
    class clsProcess
    {
        //##############################################
        /// <summary>
        /// コンストラクタ
        /// </summary>
        //##############################################
        public clsProcess()
        {
        }


        //*************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sName"></param>
        //*************************************************
        public void Mth_BackgroundKill(string sName)
        {
            foreach (var p in System.Diagnostics.Process.GetProcessesByName(sName))
            {
                if (p.MainWindowTitle == "")
                {
                    p.Kill();
                }
            }

            System.Threading.Thread.Sleep(100);

        }

    }
}