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に数式や関数を追加・取得する方法

0
Posted at

Excelは、多くの機能を備えた強力な表計算ソフトウェアです。その中でも、数式や関数は特に重要な機能です。数式や関数を使用すると、データに対してさまざまな数学的、統計的、論理的な計算を実行でき、データから有用な情報を迅速かつ正確に取得できます。

この記事では、C#およびVB.NETのコードを使用して、Excelファイルに数式や関数を追加・読み取る方法について説明します。

.NET用コンポーネントのインストール

まず、関連するコンポーネントパッケージに含まれるDLLファイルを、.NETプロジェクトの参照として追加する必要があります。必要なファイルは公式サイトからダウンロードするか、NuGet を使用してインストールできます。

PM> Install-Package Spire.XLS

C#およびVB.NETでExcelに数式や関数を追加する

Excelワークシートの特定のセルに数式や関数を追加するには、Worksheet.Range[int row, int column].Formula プロパティを使用します。

主な手順は次のとおりです。

  • Workbook クラスのインスタンスを作成します
  • Workbook.Worksheets[int index] プロパティを使用して、インデックスを指定し、対象のワークシートを取得します
  • Worksheet.Range[int row, int column].Text および Worksheet.Range[int row, int column].NumberValue プロパティを使用して、ワークシートの指定したセルにテキストデータと数値データを追加します
  • Worksheet.Range[int row, int column].Text および Worksheet.Range[int row, int column].Formula プロパティを使用して、指定したセルにテキストと数式を追加します
  • 同様に、これらのプロパティを使用して、指定したセルにテキストと関数を追加します
  • 最後に、Workbook.SaveToFile(string fileName, ExcelVersion version) メソッドを使用して、結果ファイルを保存します

完全なサンプルコードは以下のとおりです。

using Spire.Xls;

namespace AddFormulasAndFunctions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Workbook クラスのインスタンスを初期化
            Workbook workbook = new Workbook();

            // 最初のワークシートを取得
            Worksheet sheet = workbook.Worksheets[0];

            // currentRow と currentFormula の2つの変数を宣言
            int currentRow = 1;
            string currentFormula;

            // ワークシートにテキストを追加し、セルのスタイルを設定
            sheet.Range[currentRow, 1].Text = "Test Data:";
            sheet.Range[currentRow, 1].Style.Font.IsBold = true;
            sheet.Range[currentRow, 1].Style.FillPattern = ExcelPatternType.Solid;
            sheet.Range[currentRow, 1].Style.KnownColor = ExcelColors.LightGreen1;
            sheet.Range[currentRow, 1].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

            // ワークシートに数値データを追加
            sheet.Range[++currentRow, 1].NumberValue = 7.3;
            sheet.Range[currentRow, 2].NumberValue = 5;
            sheet.Range[currentRow, 3].NumberValue = 8.2;
            sheet.Range[currentRow, 4].NumberValue = 4;
            sheet.Range[currentRow, 5].NumberValue = 3;
            sheet.Range[currentRow, 6].NumberValue = 11.3;

            currentRow++;

            // ワークシートにテキストを追加し、セルのスタイルを設定
            sheet.Range[++currentRow, 1].Text = "Formulas";
            sheet.Range[currentRow, 2].Text = "Results";
            sheet.Range[currentRow, 1, currentRow, 2].Style.Font.IsBold = true;
            sheet.Range[currentRow, 1, currentRow, 2].Style.KnownColor = ExcelColors.LightGreen1;
            sheet.Range[currentRow, 1, currentRow, 2].Style.FillPattern = ExcelPatternType.Solid;
            sheet.Range[currentRow, 1, currentRow, 2].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

            // ワークシートにテキストと数式を追加
            currentFormula = "=\"Hello\"";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=300";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=3389.639421";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=false";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=1+2+3+4+5-6-7+8-9";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=33*3/4-2+10";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            currentFormula = "=Sheet1!$B$2";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            // ワークシートにテキストと関数を追加
            // AVERAGE 関数
            currentFormula = "=AVERAGE(Sheet1!$D$2:F$2)";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            // COUNT 関数
            currentFormula = "=COUNT(3,5,8,10,2,34)";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;

            // NOW 関数
            currentFormula = "=NOW()";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow, 2].Formula = currentFormula;
            sheet.Range[currentRow, 2].Style.NumberFormat = "yyyy-MM-DD";

            // SECOND 関数
            currentFormula = "=SECOND(0.503)";
            sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MINUTE 関数
            currentFormula = "=MINUTE(0.78125)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MONTH 関数
            currentFormula = "=MONTH(9)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // DAY 関数
            currentFormula = "=DAY(10)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // TIME 関数
            currentFormula = "=TIME(4,5,7)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // DATE 関数
            currentFormula = "=DATE(6,4,2)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // RAND 関数
            currentFormula = "=RAND()";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // HOUR 関数
            currentFormula = "=HOUR(0.5)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MOD 関数
            currentFormula = "=MOD(5,3)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // WEEKDAY 関数
            currentFormula = "=WEEKDAY(3)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // YEAR 関数
            currentFormula = "=YEAR(23)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // NOT 関数
            currentFormula = "=NOT(true)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // OR 関数
            currentFormula = "=OR(true)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // AND 関数
            currentFormula = "=AND(TRUE)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // VALUE 関数
            currentFormula = "=VALUE(30)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // LEN 関数
            currentFormula = "=LEN(\"world\")";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MID 関数
            currentFormula = "=MID(\"world\",4,2)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // ROUND 関数
            currentFormula = "=ROUND(7,3)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // SIGN 関数
            currentFormula = "=SIGN(4)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // INT 関数
            currentFormula = "=INT(200)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // ABS 関数
            currentFormula = "=ABS(-1.21)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // LN 関数
            currentFormula = "=LN(15)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // EXP 関数
            currentFormula = "=EXP(20)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // SQRT 関数
            currentFormula = "=SQRT(40)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // PI 関数
            currentFormula = "=PI()";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // COS 関数
            currentFormula = "=COS(9)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // SIN 関数
            currentFormula = "=SIN(45)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MAX 関数
            currentFormula = "=MAX(10,30)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // MIN 関数
            currentFormula = "=MIN(5,7)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // AVERAGE 関数
            currentFormula = "=AVERAGE(12,45)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // SUM 関数
            currentFormula = "=SUM(18,29)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // IF 関数
            currentFormula = "=IF(4,2,2)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // SUBTOTAL 関数
            currentFormula = "=SUBTOTAL(3,Sheet1!A2:F2)";
            sheet.Range[currentRow, 1].Text = "'" + currentFormula;
            sheet.Range[currentRow++, 2].Formula = currentFormula;

            // 1列目、2列目、3列目の列幅を設定
            sheet.SetColumnWidth(1, 32);
            sheet.SetColumnWidth(2, 16);
            sheet.SetColumnWidth(3, 16);

            // セルスタイルを作成
            CellStyle style = workbook.Styles.Add("Style");
            // 水平方向の配置を左揃えに設定
            style.HorizontalAlignment = HorizontalAlignType.Left;
            // ワークシートにスタイルを適用
            sheet.ApplyStyle(style);

            // 結果ファイルを保存
            workbook.SaveToFile("AddFormulasAndFunctions.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#およびVB.NETでExcelの数式と関数を読み取る

Excelワークシート内の数式や関数を読み取るには、まずワークシート内のすべてのセルを順に確認します。次に、Cell.HasFormula プロパティを使用して数式または関数が含まれているセルを特定し、CellRange.Formula プロパティを使用して、それらの数式や関数を取得します。

具体的な手順は以下のとおりです。

  • Workbook クラスのインスタンスを作成します
  • Workbook.LoadFromFile() メソッドを使用してExcelファイルを読み込みます
  • Workbook.Worksheets[sheetIndex] プロパティを使用して、インデックスを指定してワークシートを取得します
  • StringBuilder クラスのインスタンスを作成します
  • Worksheet.AllocatedRange プロパティを使用して、ワークシートの使用範囲を取得します
  • 使用範囲内のすべてのセルを順に確認します
  • Cell.HasFormula プロパティを使用して、数式または関数が含まれているセルを特定します
  • CellRange.RangeAddressLocal プロパティと CellRange.Formula プロパティを使用して、セルの名前と数式または関数を取得します
  • StringBuilder.AppendLine() メソッドを使用して、セル名と数式または関数を StringBuilder に追加します
  • File.WriteAllText() メソッドを使用して、StringBuilder の内容を .txt ファイルに書き込みます

完全なサンプルコードは以下のとおりです。

using Spire.Xls;
using System.IO;
using System.Text;

namespace ReadFormulasAndFunctions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Workbookクラスのインスタンスを初期化する
            Workbook workbook = new Workbook();
            // Excelファイルを読み込む
            workbook.LoadFromFile("AddFormulasAndFunctions.xlsx");

            // 最初のワークシートを取得する
            Worksheet sheet = workbook.Worksheets[0];

            // StringBuilderクラスのインスタンスを初期化する
            StringBuilder sb = new StringBuilder();

            // ワークシートの使用範囲にアクセスする
            CellRange usedRange = sheet.AllocatedRange;

            // 使用範囲内のすべてのセルをループ処理する
            foreach (CellRange cell in usedRange)
            {
                // 現在のセルに数式または関数が含まれているかどうかを確認する
                if (cell.HasFormula)
                {
                    // セル名を取得する
                    string cellName = cell.RangeAddressLocal;
                    // 数式または関数を取得する
                    string formula = cell.Formula;
                    // セル名と数式または関数をStringBuilderに追加する
                    sb.AppendLine(cellName + " has a formula: " + formula);
                }
            }

            // StringBuilderの内容を.txtファイルに書き込む
            File.WriteAllText("ReadFormulasAndFunctions.txt", sb.ToString());
        }
    }
}

まとめ

この記事では、C#およびVB.NETを使用して、Excelワークシート内の数式や関数を読み取る方法を紹介しました。ワークシートの使用範囲内にあるすべてのセルを確認し、HasFormula プロパティで数式や関数が含まれているセルを特定した後、Formula プロパティを使ってその内容を取得できます。さらに、StringBuilder クラスを利用して取得した情報をまとめ、テキストファイルに出力することで、Excel内の数式や関数を効率的に確認・管理できます。

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?