フッターコンテンツにスキップ
他のコンポーネントと比較する

IronXLとEPPlusの比較

この記事では、IronXLとEPPlusソフトウェアの類似点と相違点を検討します。

ほとんどの組織にとって、Microsoft Excelは非常に便利なツールであると証明されています。 データベースのようなExcelファイルにはセル内にデータが含まれており、保持する必要のあるデータの管理が非常に簡単です。

.xls.xlsxのファイル形式もExcelで使用されます。 C#言語ではExcelファイルの管理が難しいことがあります。 しかし、IronXLとEPPlusソフトウェアを使用すると、これらのプロセスを簡単に処理できます。

このソフトウェアを使用する際、Microsoft Officeは必要ありません。

Microsoft OfficeをインストールせずにC#でExcelファイルを読み取ったり作成したりできることに注意してください。本日は、簡単に実装できるいくつかの異なるオプションをご紹介します。

class="hsg-featured-snippet">

C#を使用してEPPlusでExcelファイルを読む方法

  1. EPPlus C#ライブラリをダウンロードしてインストール
  2. ExcelPackage EPPlus C#クラスを使用してExcelファイルを読む
  3. シート内の行と列の位置に基づいてデータを読み取り、変更
  4. LoadFromDataTableメソッドを使用して迅速にExcelシートを埋める
  5. EPPlus C#でExcelファイルをエクスポート

EPPlusソフトウェアとは?

EPPlusは、Office Open XMLスプレッドシートを扱うためのNuGetベースの.NET Framework/.NET Coreライブラリです。 バージョン5には、.NET Framework 3.5と.NET Core 2.0のサポートが含まれています。EPPlusは、Microsoft Excelなどの他のライブラリに依存することはありません。

EPPlusには、Office Excelドキュメントを操作するためのAPIが備わっています。 EPPlusは.NETライブラリで、Office OpenXML形式のExcelファイルを読み書きします。 このライブラリはNuGetからパッケージとして利用可能です。

このライブラリはプログラマーを念頭に置いて作成されました。 Excelまたは他のスプレッドシートライブラリに精通している開発者が、迅速にAPIを学べるようにすることが常に目標でした。 また、誰かが言ったように「IntelliSenseで勝利を掴み取る!」

EPPlusのインストール

Visual StudioからEPPlusをインストールするには、[表示] > [その他のウィンドウ] > [パッケージマネージャーコンソール]に移動し、次のコマンドを入力します:

Install-Package EPPlus

.NET CLIを利用したい場合は、昇格したコマンドプロンプトまたはPowerShellプロンプトから以下のコマンドを実行してください:

dotnet add package EPPlus

EPPlusはプロジェクトに追加できるdotnetパッケージです。

IronXLとは?

IronXLは、.NETでExcelスプレッドシートファイルを読み取り、編集し、作成するためのシンプルなC#およびVB Excel APIです。 Microsoft Officeをインストールする必要はなく、Excel Interopも必要ありません。このライブラリを使用してExcelファイルを操作することもできます。

.NET Core、.NET Framework、Xamarin、モバイル、Linux、macOS、およびAzureはすべてIronXLによってサポートされています。

あなたのスプレッドシートにデータを読み書きするための様々な方法があります。

NuGetパッケージを使用してIronXLを追加する

あなたのアカウントにIronXLパッケージを追加するための3つの方法の1つを選択できますので、あなたに最適な方法を選んでください。

  • パッケージマネージャーコンソールを使用してIronXLをインストールする

プロジェクトのパッケージマネージャーコンソールを開くために次のコマンドを使用します:

パッケージマネージャーコンソールにアクセスするには、ツール => NuGetパッケージマネージャー => パッケージマネージャーコンソールに移動します。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 1 related to NuGetパッケージを使用してIronXLを追加する

これでパッケージマネージャーコンソールに移動します。 次に、パッケージマネージャー端末で以下のコマンドを入力します:

Install-Package IronXL.Excel
class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 2 related to NuGetパッケージを使用してIronXLを追加する
  • NuGetパッケージマネージャーを使用してIronXLをインストールする

これはNuGetパッケージマネージャーをインストールするための別の方法です。 前の方法でインストールが完了している場合は、この方法を使用する必要はありません。

NuGetパッケージマネージャーにアクセスするには、ツール > NuGetパッケージマネージャー => ソリューションのNuGetパッケージを管理をドロップダウンメニューから選択します。

これでNuGetソリューションが起動します; 「参照」を選択し、IronXLを検索します。

検索バーにExcelを入力します:

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 3 related to NuGetパッケージを使用してIronXLを追加する

「インストール」ボタンをクリックするとIronXLがインストールされます。 IronXLをインストールした後、フォームに移動して開発を開始できます。

IronXLでExcelファイルを作成する

IronXLを使用して新しいExcelワークブックを作成するのはとても簡単です! たった1行のコードです! はい、これは本当です:

// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
' Create a new Excel workbook in XLSX format
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
$vbLabelText   $csharpLabel

IronXLはXLS(以前のExcelファイルバージョン)とXLSX(現在および新しいExcelファイルバージョン)形式のファイルを作成できます。

  • デフォルトのワークシートの設定

デフォルトのワークシートをセットアップするのはさらに簡単です:

// Create a worksheet named "2020 Budget" in the workbook
var sheet = workbook.CreateWorkSheet("2020 Budget");
// Create a worksheet named "2020 Budget" in the workbook
var sheet = workbook.CreateWorkSheet("2020 Budget");
' Create a worksheet named "2020 Budget" in the workbook
Dim sheet = workbook.CreateWorkSheet("2020 Budget")
$vbLabelText   $csharpLabel

上記のコードスニペットではワークシートがsheetで表され、セルの値を設定したり、Excelでできることをほぼすべて行うことができます。 Excelドキュメントを読み取り専用ファイルにコーディングし、削除操作を行うこともできます。 Excelと同様に、ワークシートをリンクすることもできます。

もしあなたがワークブックとワークシートの違いをよく知らない場合、私が明確にします。

ワークシートはワークブックに含まれています。 これは、ワークブックの中に好きなだけ多くのワークシートを置くことができることを意味します。 これをどのように行うかは後の記事で説明します。 ワークシートは行と列で構成されています。 行と列の交差部分をセルと呼び、これがExcelでやり取りするものです。

EPPlus Software ABを使用してExcelファイルを作成する

EPPlusを使用してExcelファイルを作成し、ピボットテーブル、ピボット領域の作成、条件付き書式設定、フォントの変更などの操作を実行できます。 無駄話をせずに、通常のDataTableをXLSX Excelファイルに変換し、ユーザーにダウンロードのために送信するためのソースコード全体を以下に示します:

public ActionResult ConvertToXLSX()
{
    byte[] fileData = null;

    // Replace the GetDataTable() method with your DBMS-fetching code.
    using (DataTable dt = GetDataTable())
    {
        // Create an empty spreadsheet
        using (var p = new ExcelPackage())
        {
            // Add a worksheet to the spreadsheet
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(dt.TableName);

            // Initialize rows and columns counter: note that they are 1-based!
            var row = 1;
            var col = 1;

            // Create the column names on the first line.
            // In this sample, we'll just use the DataTable column names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows into the XLS file
            foreach (DataRow r in dt.Rows)
            {
                row++;
                col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    col++;
                    ws.SetValue(row, col, r[dc].ToString());
                }

                // Alternate light-gray color for uneven rows (3, 5, 7, 9)...
                if (row % 2 != 0)
                {
                    ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                }
            }

            // Output the XLSX file
            using (var ms = new MemoryStream())
            {
                p.SaveAs(ms);
                ms.Seek(0, SeekOrigin.Begin);
                fileData = ms.ToArray();
            }
        }
    }

    string fileName = "ConvertedFile.xlsx";
    string contentType = System.Web.MimeMapping.GetMimeMapping(fileName);
    Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
    return File(fileData, contentType);
}
public ActionResult ConvertToXLSX()
{
    byte[] fileData = null;

    // Replace the GetDataTable() method with your DBMS-fetching code.
    using (DataTable dt = GetDataTable())
    {
        // Create an empty spreadsheet
        using (var p = new ExcelPackage())
        {
            // Add a worksheet to the spreadsheet
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(dt.TableName);

            // Initialize rows and columns counter: note that they are 1-based!
            var row = 1;
            var col = 1;

            // Create the column names on the first line.
            // In this sample, we'll just use the DataTable column names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows into the XLS file
            foreach (DataRow r in dt.Rows)
            {
                row++;
                col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    col++;
                    ws.SetValue(row, col, r[dc].ToString());
                }

                // Alternate light-gray color for uneven rows (3, 5, 7, 9)...
                if (row % 2 != 0)
                {
                    ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                }
            }

            // Output the XLSX file
            using (var ms = new MemoryStream())
            {
                p.SaveAs(ms);
                ms.Seek(0, SeekOrigin.Begin);
                fileData = ms.ToArray();
            }
        }
    }

    string fileName = "ConvertedFile.xlsx";
    string contentType = System.Web.MimeMapping.GetMimeMapping(fileName);
    Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
    return File(fileData, contentType);
}
Public Function ConvertToXLSX() As ActionResult
	Dim fileData() As Byte = Nothing

	' Replace the GetDataTable() method with your DBMS-fetching code.
	Using dt As DataTable = GetDataTable()
		' Create an empty spreadsheet
		Using p = New ExcelPackage()
			' Add a worksheet to the spreadsheet
			Dim ws As ExcelWorksheet = p.Workbook.Worksheets.Add(dt.TableName)

			' Initialize rows and columns counter: note that they are 1-based!
			Dim row = 1
			Dim col = 1

			' Create the column names on the first line.
			' In this sample, we'll just use the DataTable column names
			row = 1
			col = 0
			For Each dc As DataColumn In dt.Columns
				col += 1
				ws.SetValue(row, col, dc.ColumnName)
			Next dc

			' Insert the DataTable rows into the XLS file
			For Each r As DataRow In dt.Rows
				row += 1
				col = 0
				For Each dc As DataColumn In dt.Columns
					col += 1
					ws.SetValue(row, col, r(dc).ToString())
				Next dc

				' Alternate light-gray color for uneven rows (3, 5, 7, 9)...
				If row Mod 2 <> 0 Then
					ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid
					ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray)
				End If
			Next r

			' Output the XLSX file
			Using ms = New MemoryStream()
				p.SaveAs(ms)
				ms.Seek(0, SeekOrigin.Begin)
				fileData = ms.ToArray()
			End Using
		End Using
	End Using

	Dim fileName As String = "ConvertedFile.xlsx"
	Dim contentType As String = System.Web.MimeMapping.GetMimeMapping(fileName)
	Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName))
	Return File(fileData, contentType)
End Function
$vbLabelText   $csharpLabel

ご覧のとおり、これはどのASP.NET MVCコントローラにも使用できるActionResultメソッドです; もしASP.NET MVCを使用していない場合は、メソッドの内容をコピーして必要な場所に貼り付けてください(例:古典的なASP.NET、コンソールアプリケーション、Windowsフォームなど)。

コードは自己説明的であり、さまざまな処理プロセスを理解するのに役立つコメントが十分にあります。 しかしまず、ここで何をしているのかの簡単な要約:

  • カスタムデータプロバイダメソッドを使用して、DataTableオブジェクトを取得します。
  • ExcelPackageオブジェクトを構築し、それがXLSXファイルのEPPlusの主要なコンテナです。
  • ExcelPackageExcelWorksheetを追加し、データが入力されるワークシートにします。
  • ヘッダー行を作成するためにDataTable列を繰り返し、ワークシートの最初の行に追加します。
  • DataTable行を繰り返し、各行をワークシート行に1行ずつ追加します(行2から開始)。これにより各DataTable行がワークシート行に対応します。
  • 変換が完了した際のExcelPackageバイナリデータを格納するためにMemoryStreamを構築し、バイト配列に変換します。
  • HTML応答を作成し、Content-Disposition添付ファイルを使用してXLSXファイルをユーザーに送信します。これによりブラウザは自動的にファイルをダウンロードします。

この場合、IronXLが勝利します。なぜなら、生成プロセスが非常に簡単で、1行のコードで済みます; これにより、EPPlusが提供する多数のコード行を通過するのが退屈であり、デバッグが難しいのに対し、IronXLを使用することで時間の節約とデバッグが可能になります。

EPPlus Software ABがExcelファイルを書き込む方法

EPPlusはExcelファイルの取り扱いをサポートしています。 これはExcelファイルを読み書きする.netライブラリです。

  • Excelファイルを読む

そのためには、まずパッケージEPPlusをインストールする必要があります:「ツール」-> 「NuGetパッケージマネージャー」-> 「このソリューションのNuGetを管理」 -> 「EPPlusをインストール」。 「参照」タブで「EPPlus」を検索し、NuGetパッケージをインストールします。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 4 related to EPPlus Software ABがExcelファイルを書き込む方法

あなたがパッケージをインストールした後、コンソールアプリケーション「Program.cs」で以下のコードを使用できます。

using OfficeOpenXml;
using System;
using System.IO;

namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Provide file path
            FileInfo existingFile = new FileInfo(@"D:\sample_XLSX.xlsx");
            // Use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                // Get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  // Get Column Count
                int rowCount = worksheet.Dimension.End.Row;     // Get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        // Print data, based on row and columns position
                        Console.WriteLine("Row:" + row + " Column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}
using OfficeOpenXml;
using System;
using System.IO;

namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Provide file path
            FileInfo existingFile = new FileInfo(@"D:\sample_XLSX.xlsx");
            // Use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                // Get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  // Get Column Count
                int rowCount = worksheet.Dimension.End.Row;     // Get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        // Print data, based on row and columns position
                        Console.WriteLine("Row:" + row + " Column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}
Imports OfficeOpenXml
Imports System
Imports System.IO

Namespace ReadExcelInCsharp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Provide file path
			Dim existingFile As New FileInfo("D:\sample_XLSX.xlsx")
			' Use EPPlus
			Using package As New ExcelPackage(existingFile)
				' Get the first worksheet in the workbook
				Dim worksheet As ExcelWorksheet = package.Workbook.Worksheets(1)
				Dim colCount As Integer = worksheet.Dimension.End.Column ' Get Column Count
				Dim rowCount As Integer = worksheet.Dimension.End.Row ' Get row count
				For row As Integer = 1 To rowCount
					For col As Integer = 1 To colCount
						' Print data, based on row and columns position
						Console.WriteLine("Row:" & row & " Column:" & col & " Value:" & worksheet.Cells(row, col).Value?.ToString().Trim())
					Next col
				Next row
			End Using
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

以下は、EPPlusを使用してC#で作業している例のコンソールアプリケーション出力です。 EPPlusを使用してC#で読み込むためのxlsxファイルはこちらです。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 5 related to EPPlus Software ABがExcelファイルを書き込む方法

複数のソースからデータをロードするための以下の方法に、"cells"プロパティ(ExcelRange)を使用してアクセスできます。

  • CSVテキストファイルを読む - LoadFromTextLoadFromTextAsyncを使用してシート上の範囲にデータをロードします。
  • LoadFromDataReaderAsyncLoadFromDataReader — DataReaderからデータフィールドを範囲にロードします。
  • LoadFromDataTableDataTableから範囲にデータをロードします。 XML(例が提供されています)やデータベースを含むさまざまなソースからデータをインポートできます。
  • LoadFromCollection — 反射でIEnumerableから範囲にデータをロードします。
  • 属性を持つLoadFromCollection — 反射でIEnumerableから範囲またはテーブルにデータをロードします。 スタイル、数値フォーマット、数式、その他のプロパティは属性によって指定されます。
  • LoadFromDictionariesExpandoObject/ダイナミックオブジェクト(IDictionary<string, object>インターフェース経由)のIEnumerableから範囲にデータをロードします。 JSONデータをインポートするのに便利であり、例が含まれています。
  • LoadFromArrays — オブジェクトのIEnumerableから範囲にデータをロードします。それぞれのオブジェクト配列はワークシート上の行に対応します。

これらの方法を使用する場合、オプションでExcelテーブルを生成するパラメーターを指定することができます。 サンプルプロジェクトSample-.NET FrameworkまたはSample-.NET Frameworkのサンプル4と5により広範な例が含まれています。

  • Excelファイルを書く

次に、新しいExcelファイルにデータをエクスポートできるかどうかを見てみましょう。

Excelドキュメントとして保存したいサンプルデータ/オブジェクトはこちらです。

List<UserDetails> persons = new List<UserDetails>()
{
    new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
    new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
    new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
    new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
};
List<UserDetails> persons = new List<UserDetails>()
{
    new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
    new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
    new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
    new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
};
Dim persons As New List(Of UserDetails)() From {
	New UserDetails() With {
		.ID="9999",
		.Name="ABCD",
		.City ="City1",
		.Country="USA"
	},
	New UserDetails() With {
		.ID="8888",
		.Name="PQRS",
		.City ="City2",
		.Country="INDIA"
	},
	New UserDetails() With {
		.ID="7777",
		.Name="XYZZ",
		.City ="City3",
		.Country="CHINA"
	},
	New UserDetails() With {
		.ID="6666",
		.Name="LMNO",
		.City ="City4",
		.Country="UK"
	}
}
$vbLabelText   $csharpLabel

必要な情報を含む新しいExcelファイルを作成するために、ExcelPackageクラスを使用する必要があります。 ファイルにデータを書き込み、新しいExcelスプレッドシートを生成するには、ほんの数行のコードが必要です。 次の行に注目してください:これはDataTablesをExcelシートにロードする魔法を行います。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 6 related to EPPlus Software ABがExcelファイルを書き込む方法

シンプルさを保つため、私は同じプロジェクトフォルダ内に新しいスプレッドシートファイルを生成しています(Excelファイルはプロジェクトの'bin'フォルダに生成されます)。 ソースコードは以下です:

private static void WriteToExcel(string path)
{
    // Let use below test data for writing it to excel
    List<UserDetails> persons = new List<UserDetails>()
    {
        new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
        new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
        new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
        new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
    };

    // Let's convert our object data to Datatable for a simplified logic.
    // Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
    DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
    FileInfo filePath = new FileInfo(path);
    using (var excelPack = new ExcelPackage(filePath))
    {
        var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
        ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
        excelPack.Save();
    }
}
private static void WriteToExcel(string path)
{
    // Let use below test data for writing it to excel
    List<UserDetails> persons = new List<UserDetails>()
    {
        new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
        new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
        new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
        new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
    };

    // Let's convert our object data to Datatable for a simplified logic.
    // Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
    DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
    FileInfo filePath = new FileInfo(path);
    using (var excelPack = new ExcelPackage(filePath))
    {
        var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
        ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
        excelPack.Save();
    }
}
Private Shared Sub WriteToExcel(ByVal path As String)
	' Let use below test data for writing it to excel
	Dim persons As New List(Of UserDetails)() From {
		New UserDetails() With {
			.ID="9999",
			.Name="ABCD",
			.City ="City1",
			.Country="USA"
		},
		New UserDetails() With {
			.ID="8888",
			.Name="PQRS",
			.City ="City2",
			.Country="INDIA"
		},
		New UserDetails() With {
			.ID="7777",
			.Name="XYZZ",
			.City ="City3",
			.Country="CHINA"
		},
		New UserDetails() With {
			.ID="6666",
			.Name="LMNO",
			.City ="City4",
			.Country="UK"
		}
	}

	' Let's convert our object data to Datatable for a simplified logic.
	' Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
	Dim table As DataTable = CType(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (GetType(DataTable))), DataTable)
	Dim filePath As New FileInfo(path)
	Using excelPack = New ExcelPackage(filePath)
		Dim ws = excelPack.Workbook.Worksheets.Add("WriteTest")
		ws.Cells.LoadFromDataTable(table, True, OfficeOpenXml.Table.TableStyles.Light8)
		excelPack.Save()
	End Using
End Sub
$vbLabelText   $csharpLabel

上記のAPIコールでのデータ妥当性検証に続いて、上記のカスタムオブジェクトが適切なExcel列と行に変換され、新しいExcelファイルが生成されます。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 7 related to EPPlus Software ABがExcelファイルを書き込む方法

上記の即使用可能なAPIは.NET Coreコンソール、テストプロジェクト、またはASP.NET Coreアプリケーションで使用でき、ニーズに合わせてロジックを変更できます。

これらの技術には"cells"プロパティ(ExcelRange)を使用してアクセスできます:

  • ToTextとToTextAsync — 範囲からCSV文字列を作成します。
  • 範囲をCSVファイルに書き込む - SaveToTextSaveToTextAsyncを使用します。
  • データを範囲からシステムにエクスポートするToDataTableメソッドを使用します。 DataTable
  • GetValue — データ型のオプションで値を表示します。
  • Value — 範囲の値を返したり設定したりします。

GetValueSetValueメソッドも直接ワークシートオブジェクトで使用できます。 (これは範囲での読み書きより若干良い結果を提供します):

  • GetValue — データ型を指定して単一のセルの値を取得します。
  • SetValue — 単一のセルの値を変更します。

ワークシートからデータをクエリするために、セルプロパティはIEnumerableインターフェースを実装しているため、Linqを使用できます。

IronXLを使用してOffice Open XML形式XLSXを開いて書き込む

IronXLはC#の開発者がExcelやピボットテーブル、その他のスプレッドシートファイルを迅速かつ簡単に取り扱うための.NETライブラリです。

Office Interopは必要ありません。 特に依存関係や、CoreやAzure上にMicrosoft Officeをインストールする必要はありません。

IronXLは.NET coreおよび.NETフレームワーク用の著名なC#およびVB.NET xlスプレッドシートライブラリです。

  • Excelファイルを読む
  • 読み込むワークシート

ExcelシートはWorkBookクラスで表されます。 WorkBookを使用して、C#でピボットテーブルさえ含むExcelファイルを開きます。 Excelファイルを読み込み、その場所を選択します(.xlsx)。

/**
 Load WorkBook
 **/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
/**
 Load WorkBook
 **/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
'''
''' Load WorkBook
''' *
Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
$vbLabelText   $csharpLabel

ワークシートオブジェクトは多数のワークブックに見つかります。 これらはExcelドキュメントのワークシートです。 シートにワークシートが含まれている場合、名前WorkBookを使用してそれらをGetWorkSheetで見つけます。

var worksheet = workbook.GetWorkSheet("GDPByCountry");
var worksheet = workbook.GetWorkSheet("GDPByCountry");
Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
$vbLabelText   $csharpLabel
  • 自分のワークブックを作成する

メモリ内に新しいワークブックを生成するために、シートタイプと共に新しいWorkBookを構築します。

/**
 Create WorkBook
 **/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
/**
 Create WorkBook
 **/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
'''
''' Create WorkBook
''' *
Dim workbook As New WorkBook(ExcelFileFormat.XLSX)
$vbLabelText   $csharpLabel

古いMicrosoft Excelスプレッドシートの場合はExcelFileFormat.XLS(95以前)を使用します。

ワークシートを自分で作成する

各「ワークブック」には多数の「ワークシート」が含まれます。「ワークシート」は単一のデータシートで、「ワークブック」はワークシートのコレクションです。 Excelでは、これが2つのワークシートを持つ1つのワークブックの見え方です。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 8 related to IronXLを使用してOffice Open XML形式XLSXを開いて書き込む

あなたが構築できる新しいWorkSheetの名前がWorkBookです。

var worksheet = workbook.CreateWorkSheet("Countries");
var worksheet = workbook.CreateWorkSheet("Countries");
Dim worksheet = workbook.CreateWorkSheet("Countries")
$vbLabelText   $csharpLabel

ワークシートの名前をCreateWorkSheetに渡します。

セルの範囲を取得する

「Cell」オブジェクトの2次元コレクションは「Range」クラスで表されます。 それは特定のExcelセルの範囲を示します。 WorkSheetオブジェクトでの文字列インデクサを使用して範囲を取得できます。

var range = worksheet["D2:D101"];
var range = worksheet["D2:D101"];
Dim range = worksheet("D2:D101")
$vbLabelText   $csharpLabel

引数テキストはセルの座標(例:「A1」)やセルの範囲(例:「B2:E5」)として指定されます。 GetRangeをワークシートから呼び出すこともできます。

  • 範囲内のセルの値を編集する

範囲内のセルの値を読み取ったり編集したりするさまざまな方法があります。 数がわかっている場合はForループを使用します。 ここからセルのスタイリングも行えます。

/**
 Edit Cell Values in Range
 **/
 // Iterate through the rows
for (var y = 2; y <= 101; y++)
{
    var result = new PersonValidationResult { Row = y };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{y}:E{y}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day [suffix], Year (4 = E)
    var rawDate = (string) cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
/**
 Edit Cell Values in Range
 **/
 // Iterate through the rows
for (var y = 2; y <= 101; y++)
{
    var result = new PersonValidationResult { Row = y };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{y}:E{y}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day [suffix], Year (4 = E)
    var rawDate = (string) cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
'''
''' Edit Cell Values in Range
''' *
 ' Iterate through the rows
For y = 2 To 101
	Dim result = New PersonValidationResult With {.Row = y}
	results.Add(result)

	' Get all cells for the person
	Dim cells = worksheet($"A{y}:E{y}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day [suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next y
$vbLabelText   $csharpLabel

スプレッドシートのデータをバリデートする

IronXLを使用してデータシートをバリデートします。 DataValidationサンプルは、libphonenumber-CSharpを使用して電話番号を、標準的なC# APIを使用してメールアドレスや日付をバリデートします。

/**
 Validate Spreadsheet Data
 **/
 // Iterate through the rows
for (var i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{i}:E{i}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day [suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
/**
 Validate Spreadsheet Data
 **/
 // Iterate through the rows
for (var i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{i}:E{i}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day [suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
'''
''' Validate Spreadsheet Data
''' *
 ' Iterate through the rows
For i = 2 To 101
	Dim result = New PersonValidationResult With {.Row = i}
	results.Add(result)

	' Get all cells for the person
	Dim cells = worksheet($"A{i}:E{i}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day [suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next i
$vbLabelText   $csharpLabel

上記のコードはスプレッドシートの行を繰り返し処理し、セルをリストとして取得します。各バリデートメソッドはセルの値を確認し、値が不正な場合にエラーを返します。

このコードは新しいシートを作成し、ヘッダーを指定し、不正なデータログを保持できるようにエラーメッセージの結果を生成します。

var resultsSheet = workbook.CreateWorkSheet("Results");

resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

for (var i = 0; i < results.Count; i++)
{
    var result = results[i];
    resultsSheet[$"A{i + 2}"].Value = result.Row;
    resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{i + 2}"].Value = result.PhoneNumberErrorMessage;
    resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;
    resultsSheet[$"E{i + 2}"].Value = result.DateErrorMessage;
}

workbook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");
var resultsSheet = workbook.CreateWorkSheet("Results");

resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

for (var i = 0; i < results.Count; i++)
{
    var result = results[i];
    resultsSheet[$"A{i + 2}"].Value = result.Row;
    resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{i + 2}"].Value = result.PhoneNumberErrorMessage;
    resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;
    resultsSheet[$"E{i + 2}"].Value = result.DateErrorMessage;
}

workbook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");
Dim resultsSheet = workbook.CreateWorkSheet("Results")

resultsSheet("A1").Value = "Row"
resultsSheet("B1").Value = "Valid"
resultsSheet("C1").Value = "Phone Error"
resultsSheet("D1").Value = "Email Error"
resultsSheet("E1").Value = "Date Error"

For i = 0 To results.Count - 1
	Dim result = results(i)
	resultsSheet($"A{i + 2}").Value = result.Row
	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No")
	resultsSheet($"C{i + 2}").Value = result.PhoneNumberErrorMessage
	resultsSheet($"D{i + 2}").Value = result.EmailErrorMessage
	resultsSheet($"E{i + 2}").Value = result.DateErrorMessage
Next i

workbook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")
$vbLabelText   $csharpLabel

Entity Frameworkを使用してデータをエクスポートする

IronXLを使用してExcelスプレッドシートをデータベースに変換したり、データをデータベースにエクスポートしたりします。 ExcelToDBサンプルは国ごとのGDPを含むスプレッドシートを読み込み、それをSQLiteにエクスポートします。

EntityFrameworkを用いてデータベースを作成し、その後データを行ごとにエクスポートします。

SQLite Entity Framework NuGetパッケージをインストールする必要があります。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 9 related to IronXLを使用してOffice Open XML形式XLSXを開いて書き込む

EntityFrameworkを使用してデータベースにデータをエクスポートできるモデルオブジェクトを構築できます。

public class Country
{
    [Key]
    public Guid Key { get; set; }
    public string Name { get; set; }
    public decimal GDP { get; set; }
}
public class Country
{
    [Key]
    public Guid Key { get; set; }
    public string Name { get; set; }
    public decimal GDP { get; set; }
}
Public Class Country
	<Key>
	Public Property Key() As Guid
	Public Property Name() As String
	Public Property GDP() As Decimal
End Class
$vbLabelText   $csharpLabel

別のデータベースを使用するには、適切なNuGetパッケージをインストールし、UseSqLite相当のもの(UseMySQLUseSqlServerなど)を探します。

/**
 Export Data using Entity Framework
 **/
public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    public CountryContext()
    {
        // TODO: Make async
        Database.EnsureCreated();
    }

    /// <summary>
    /// Configure context to use Sqlite
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connection = new SqliteConnection($"Data Source=Country.db");
        connection.Open();

        var command = connection.CreateCommand();

        // Create the database if it doesn't already exist
        command.CommandText = $"PRAGMA foreign_keys = ON;";
        command.ExecuteNonQuery();

        optionsBuilder.UseSqlite(connection);

        base.OnConfiguring(optionsBuilder);
    }
}
/**
 Export Data using Entity Framework
 **/
public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    public CountryContext()
    {
        // TODO: Make async
        Database.EnsureCreated();
    }

    /// <summary>
    /// Configure context to use Sqlite
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connection = new SqliteConnection($"Data Source=Country.db");
        connection.Open();

        var command = connection.CreateCommand();

        // Create the database if it doesn't already exist
        command.CommandText = $"PRAGMA foreign_keys = ON;";
        command.ExecuteNonQuery();

        optionsBuilder.UseSqlite(connection);

        base.OnConfiguring(optionsBuilder);
    }
}
'''
''' Export Data using Entity Framework
''' *
Public Class CountryContext
	Inherits DbContext

	Public Property Countries() As DbSet(Of Country)

	Public Sub New()
		' TODO: Make async
		Database.EnsureCreated()
	End Sub

	''' <summary>
	''' Configure context to use Sqlite
	''' </summary>
	''' <param name="optionsBuilder"></param>
	Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
		Dim connection = New SqliteConnection($"Data Source=Country.db")
		connection.Open()

		Dim command = connection.CreateCommand()

		' Create the database if it doesn't already exist
		command.CommandText = $"PRAGMA foreign_keys = ON;"
		command.ExecuteNonQuery()

		optionsBuilder.UseSqlite(connection)

		MyBase.OnConfiguring(optionsBuilder)
	End Sub
End Class
$vbLabelText   $csharpLabel

CountryContextを生成し、範囲を繰り返して各エントリを作成した後、SaveChangesAsyncでデータをデータベースに保存します。

public async Task ProcessAsync()
{
    // Get the first worksheet
    var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
    var worksheet = workbook.GetWorkSheet("GDPByCountry");

    // Create the database connection
    using (var countryContext = new CountryContext())
    {
        // Iterate through all the cells
        for (var i = 2; i <= 213; i++)
        {
            // Get the range from A-B
            var range = worksheet[$"A{i}:B{i}"].ToList();

            // Create a Country entity to be saved to the database
            var country = new Country
            {
                Name = (string)range[0].Value,
                GDP = (decimal)(double)range[1].Value
            };

            // Add the entity
            await countryContext.Countries.AddAsync(country);
        }

        // Commit changes to the database
        await countryContext.SaveChangesAsync();
    }
}
public async Task ProcessAsync()
{
    // Get the first worksheet
    var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
    var worksheet = workbook.GetWorkSheet("GDPByCountry");

    // Create the database connection
    using (var countryContext = new CountryContext())
    {
        // Iterate through all the cells
        for (var i = 2; i <= 213; i++)
        {
            // Get the range from A-B
            var range = worksheet[$"A{i}:B{i}"].ToList();

            // Create a Country entity to be saved to the database
            var country = new Country
            {
                Name = (string)range[0].Value,
                GDP = (decimal)(double)range[1].Value
            };

            // Add the entity
            await countryContext.Countries.AddAsync(country);
        }

        // Commit changes to the database
        await countryContext.SaveChangesAsync();
    }
}
Public Async Function ProcessAsync() As Task
	' Get the first worksheet
	Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
	Dim worksheet = workbook.GetWorkSheet("GDPByCountry")

	' Create the database connection
	Using countryContext As New CountryContext()
		' Iterate through all the cells
		For i = 2 To 213
			' Get the range from A-B
			Dim range = worksheet($"A{i}:B{i}").ToList()

			' Create a Country entity to be saved to the database
			Dim country As New Country With {
				.Name = CStr(range(0).Value),
				.GDP = CDec(CDbl(range(1).Value))
			}

			' Add the entity
			Await countryContext.Countries.AddAsync(country)
		Next i

		' Commit changes to the database
		Await countryContext.SaveChangesAsync()
	End Using
End Function
$vbLabelText   $csharpLabel

スプレッドシートに数式を組み込む

Formulaプロパティを使用してセルの数式を設定できます。

// Iterate through all rows with a value
for (var y = 2; y < i; y++)
{
    // Get the C cell
    var cell = sheet[$"C{y}"].First();

    // Set the formula for the Percentage of Total column
    cell.Formula = $"=B{y}/B{i}";
}
// Iterate through all rows with a value
for (var y = 2; y < i; y++)
{
    // Get the C cell
    var cell = sheet[$"C{y}"].First();

    // Set the formula for the Percentage of Total column
    cell.Formula = $"=B{y}/B{i}";
}
' Iterate through all rows with a value
Dim y = 2
Do While y < i
	' Get the C cell
	Dim cell = sheet($"C{y}").First()

	' Set the formula for the Percentage of Total column
	cell.Formula = $"=B{y}/B{i}"
	y += 1
Loop
$vbLabelText   $csharpLabel

C列のコードは各州を繰り返し、パーセンテージ合計を計算します。

APIからデータをスプレッドシートにダウンロードする

次の呼び出しでRestClient.Netを使用してREST呼び出しを行います。 JSONをダウンロードし、それをRestCountryタイプの「リスト」に変換します。REST APIからのデータは、各国を反復処理することで簡単にExcelファイルに保存することができます。

/**
 Data API to Spreadsheet
 **/
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
/**
 Data API to Spreadsheet
 **/
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
'''
''' Data API to Spreadsheet
''' *
Dim client As New Client(New Uri("https://restcountries.eu/rest/v2/"))
Dim countries As List(Of RestCountry) = Await client.GetAsync(Of List(Of RestCountry))()
$vbLabelText   $csharpLabel

APIからのJSONデータは以下のようになります。

class="content-img-align-center">
class="center-image-wrapper"> Epplus Read Create Excel Alternative 10 related to IronXLを使用してOffice Open XML形式XLSXを開いて書き込む

次のコードは、国名、人口、地域、数値コード、トップ3の言語でスプレッドシートを埋めます。

for (var i = 2; i < countries.Count; i++)
{
    var country = countries[i];

    // Set the basic values
    worksheet[$"A{i}"].Value = country.name;
    worksheet[$"B{i}"].Value = country.population;
    worksheet[$"G{i}"].Value = country.region;
    worksheet[$"H{i}"].Value = country.numericCode;

    // Iterate through languages
    for (var x = 0; x < 3; x++)
    {
        if (x > (country.languages.Count - 1)) break;

        var language = country.languages[x];

        // Get the letter for the column
        var columnLetter = GetColumnLetter(4 + x);

        // Set the language name
        worksheet[$"{columnLetter}{i}"].Value = language.name;
    }
}
for (var i = 2; i < countries.Count; i++)
{
    var country = countries[i];

    // Set the basic values
    worksheet[$"A{i}"].Value = country.name;
    worksheet[$"B{i}"].Value = country.population;
    worksheet[$"G{i}"].Value = country.region;
    worksheet[$"H{i}"].Value = country.numericCode;

    // Iterate through languages
    for (var x = 0; x < 3; x++)
    {
        if (x > (country.languages.Count - 1)) break;

        var language = country.languages[x];

        // Get the letter for the column
        var columnLetter = GetColumnLetter(4 + x);

        // Set the language name
        worksheet[$"{columnLetter}{i}"].Value = language.name;
    }
}
For i = 2 To countries.Count - 1
	Dim country = countries(i)

	' Set the basic values
	worksheet($"A{i}").Value = country.name
	worksheet($"B{i}").Value = country.population
	worksheet($"G{i}").Value = country.region
	worksheet($"H{i}").Value = country.numericCode

	' Iterate through languages
	For x = 0 To 2
		If x > (country.languages.Count - 1) Then
			Exit For
		End If

		Dim language = country.languages(x)

		' Get the letter for the column
		Dim columnLetter = GetColumnLetter(4 + x)

		' Set the language name
		worksheet($"{columnLetter}{i}").Value = language.name
	Next x
Next i
$vbLabelText   $csharpLabel

IronXLを使用してExcelファイルを開く

Excelファイルを起動した後、1枚目のシートの1つ目のセルを読み、印刷する最初の数行を追加します。

static void Main(string[] args)
{
    var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
    var sheet = workbook.WorkSheets.First();
    var cell = sheet["A1"].StringValue;
    Console.WriteLine(cell);
}
static void Main(string[] args)
{
    var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
    var sheet = workbook.WorkSheets.First();
    var cell = sheet["A1"].StringValue;
    Console.WriteLine(cell);
}
Shared Sub Main(ByVal args() As String)
	Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx")
	Dim sheet = workbook.WorkSheets.First()
	Dim cell = sheet("A1").StringValue
	Console.WriteLine(cell)
End Sub
$vbLabelText   $csharpLabel

IronXLを使って新しいExcelファイルを作成します。

/**
 Create Excel File
 **/
static void Main(string[] args)
{
    var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
    newXLFile.Metadata.Title = "IronXL New File";
    var newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet");
    newWorkSheet["A1"].Value = "Hello World";
    newWorkSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
    newWorkSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
}
/**
 Create Excel File
 **/
static void Main(string[] args)
{
    var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
    newXLFile.Metadata.Title = "IronXL New File";
    var newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet");
    newWorkSheet["A1"].Value = "Hello World";
    newWorkSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
    newWorkSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
}
'''
''' Create Excel File
''' *
Shared Sub Main(ByVal args() As String)
	Dim newXLFile = WorkBook.Create(ExcelFileFormat.XLSX)
	newXLFile.Metadata.Title = "IronXL New File"
	Dim newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet")
	newWorkSheet("A1").Value = "Hello World"
	newWorkSheet("A2").Style.BottomBorder.SetColor("#ff6600")
	newWorkSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed
End Sub
$vbLabelText   $csharpLabel

その後CSV、JSON、またはXMLとして、それぞれのコードを使用して保存することができます。

例えば、XMLとして保存するには.xml

XMLに保存するには、SaveAsXmlを以下のように使用します:

newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
newXLFile.SaveAsXml($"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML")
$vbLabelText   $csharpLabel

結果は以下のようになります:

<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>
<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>
XML

Excelファイルを読むのはIronXLがEPPlusよりも簡単です。 IronXLには、ワークブック内のすべての列、行、セルにアクセスするのに必要なすべてを網羅する短縮コードがありますが、EPPlusでは列と行を読み込むための特定の行が必要です。

IronXLはExcelドキュメントの操作に関してよりインテリジェントです。 それは、必要に応じていつでも多くのシートを作成したり、複数のワークシートやワークブックからデータを読み取ったりする上での上位手を提供し、IronXLを使用することでExcelワークブックのデータをデータベースに満たすことも可能です。

EPPlusおよびIronXLのライセンスと価格

EPPlusのライセンスモデルと価格

EPPlusは、非商業用ライセンスモデルまたはPolyformの商業用ライセンスモデルのいずれかで使用できます。

商業用ライセンス

これらは永続的およびサブスクリプションベースのフォーマットで利用でき、1か月から2年間の期間に対応しています。

すべてのライセンスカテゴリーにおいて、ライセンス期間中のサポートセンターを通じたサポートおよびNuGetを通じたアップグレードが含まれています。

EPPlusは1ライセンスあたり1つの開発者が必要です。 ライセンスは個々のユーザーに発行され、共有することはできません。 一般的なガイドラインとして、EPPlusを直接使用するコードの作成やデバッグが必要である人はすべて商業ライセンスを所有するべきです。

EPPlusの機能をAPIを通じて内部的に提供する場合(例:APIを介してその能力を提供する)、あなたの会社はEPPlusをサービスとして提供する内部ユーザー(開発者)の数以内でサブスクリプションを購入する必要があります。

サブスクリプション

サブスクリプションで常に最新バージョンを使用できますが、開発にEPPlusを使用する限り有効なライセンスが必要です。 ライセンス期間終了時には、支払いが完了した後にライセンスが自動的に請求および更新されます。 ライセンス期間終了時にサブスクリプションをキャンセルし、新しいものをいつでも開始することができます。サブスクリプションはインターネットでのみ購入できます。

EPPlusは商業用に使用できます。 ライセンスは1社あたり1つの開発者が使用でき、デプロイメントの場所に無制限の数が許可されます。 毎年の購入可能なライセンスの数は増減可能であり、ライセンスは各年末に一時停止またはキャンセルできます。

32日の試用期間がオプションとして利用可能です。

価格: $299から年間スタート。

利用ごとの支払いが可能

1つの組織内で、デプロイメント場所に無制限の開発者あたりの価格で、Stripeの請求を受けられます。 毎月の購入可能なライセンス数は増減可能であり、ライセンスは月末に一時停止またはキャンセルできます。

価格: $29から月額スタート。

永続ライセンス

永続ライセンスを持つと、新しいバージョンにアップグレードし、一定期間サポートを受けられます。その後、この期間中にリリースされたバージョンを使用してソフトウェアを開発し続けることができます。

同じ会社内でデプロイメントの場所に無制限で開発者あたりの価格。 サポート/アップグレード期間にリリースされたすべてのEPPlusバージョンの無期限使用。

32日の試用期間がオプションとして利用可能です。

価格: $599から年間スタート。

パッケージ

最初のサポートおよびアップグレードの期間を持つ永続ライセンスオプションが利用可能です。 この期間中にリリースされたバージョンを使用してソフトウェアを開発し続けることができます。

価格: $4,295から年間スタート。

Polyform用の非商業用ライセンス

EPPlusはバージョン5からPolyformの非商業用ライセンスのもとでライセンスされています。これはコードがオープンソースであり、非商業的な用途で使用できることを意味します。 詳細は彼らのウェブサイトで確認できます。

IronXLのライセンスモデルと価格

永続ライセンス:各ライセンスは一度購入され、更新を必要としません。

無料サポート&製品アップデート:各ライセンスは1年間の無料製品更新とサポートが付きます。 いかなる瞬間でも拡張機能を購入することが可能です。 拡張機能を閲覧できます。

即時ライセンス:登録済みライセンスキーは支払いが受け取られるとすぐに送信されます。

IronXLの.NETライセンスに関して何か質問があれば、弊社のIron Softwareライセンススペシャリストにお問い合わせください。

すべてのライセンスは永続的であり、開発、ステージング、本番環境に適用されます。

ライト - 各ライセンスは一組織内の1人のソフトウェア開発者がIron Softwareを1か所で使用することを許可します。 Iron Softwareは単一のWebアプリケーション、イントラネットアプリケーション、またはデスクトップソフトウェアプログラムで使用できます。 ライセンスは譲渡不可で、組織や代理店/クライアントの関係を外れて共有することはできません。このライセンスタイプは、他のすべてのライセンスタイプと同様に、契約で明示的に付与されていないすべての権利、OEM再配布、Iron Softwareを追加の保証を購入せずにSaaSとして使用することを明示的に除外します。

価格: $489から年間スタート。

プロフェッショナルライセンス - 事前に決まった数のソフトウェア開発者が、一組織内で最大10か所までIron Softwareを使用できるようにします。 The Iron Software can be used in as many websites, intranet applications, or desktop software applications as you like. ライセンスは譲渡不可で、組織や代理店/クライアントの関係を外れて共有することはできません。このライセンスタイプは、他のすべてのライセンスタイプと同様に、契約で明示的に付与されていないすべての権利、OEM再配布、Iron Softwareを追加の保証を購入せずにSaaSとして使用することを明示的に除外します。

価格: $976から年間スタート。

無制限ライセンス - 業務用にIron Softwareを何人のソフトウェア開発者も無制限の数の場所で利用できるようにします。 The Iron Software can be used in as many websites, intranet applications, or desktop software applications as you like. ライセンスは譲渡不可で、組織や代理店/クライアントの関係を外れて共有することはできません。このライセンスタイプは、他のすべてのライセンスタイプと同様に、契約で明示的に付与されていないすべての権利、OEM再配布、Iron Softwareを追加の保証を購入せずにSaaSとして使用することを明示的に除外します。

ロイヤルティフリーの再配布 - Iron Softwareを多様なパッケージ化された商用製品の一部として(ロイヤルティを支払うことなく)再配布することを許可します。 SaaSソフトウェアサービス内でのIron Softwareの配備を許可します。

価格: $2939から年間スタート。

結論

結論として、IronXLはEPPlusよりも実用的です。なぜなら、短いコード行と、XML、HTML、JSONなどのエクスポートの機会をより多く提供し、Excelテーブルを必要なようにナビゲートする柔軟性を提供するからです。 IronXLはワークブックデータをデータベースに統合することも可能です。 さらに、ドキュメントが編集されるたびに数式を再計算する直感的なシステムを備え、WorkSheet["A1:B10"]構文を使用して直感的なレンジ設定を提供します。 シートの機能には、Excelと連動する数式が含まれており、シートが編集されるたびに再計算されます。 セルデータのフォーマットには、複数のテキスト、数字、数式、日付、通貨、パーセンテージ、科学記法、時間があります。カスタムフォーマットには、範囲、列、行などの異なる並べ替え方法があります。 そのセルスタイルには、さまざまなフォント、サイズ、背景パターン、境界線、対数、アライメントがあります。

ご注意EPPlusはその権利保有者の登録商標です。 このサイトは、EPPlusとは提携しておらず、賛同、または後援されていません。] すべての製品名、ロゴ、およびブランドは各所有者の所有物です。 比較は情報提供のみを目的としており、執筆時点で公開されている情報を反映しています。

よくある質問

Microsoft Officeを使用せずにExcelファイルを作成するにはどうすればよいですか?

Microsoft Officeを使用せずにExcelファイルを作成するにはIronXLを使用できます。IronXLはC#およびVB.NETでExcelスプレッドシートを読み込み、編集、作成するためのシンプルなAPIを提供します。

EPPlusよりIronXLを使用する利点は何ですか?

IronXLはより直感的なAPIを提供し、XML、HTML、JSONなどの複数のファイル形式をサポートし、高度なスタイリングと数式の再計算を可能にします。これにより、EPPlusと比較して、開発者にとってより実用的で柔軟性があります。

IronXLを使用してExcelデータを操作し、異なる形式にエクスポートすることは可能ですか?

はい、IronXLはExcelデータをXML、HTML、JSONなどの異なる形式にエクスポートすることをサポートしており、データベースや他のアプリケーションとの統合が容易です。

IronXLでExcelの数式をどのように処理しますか?

IronXLは直感的な数式の再計算をサポートしており、ドキュメントが編集されるたびに数式が自動的に更新されるため、Excelの数式を効率的に管理するシステムを提供します。

IronXLのライセンスオプションは何ですか?

IronXLは、開発、ステージング、プロダクション環境向けに永続ライセンスを提供し、1開発者あたり年間$489からの価格設定となっています。1年間の無料アップデートとサポートが含まれています。

EPPlusはピボットテーブルの作成や条件付き書式の適用に使用できますか?

はい、EPPlusはピボットテーブルの作成や条件付き書式の適用をサポートしていますが、一般的にIronXLよりも複雑なコードを必要とします。

IronXLはクロスプラットフォーム開発をどのようにサポートしますか?

IronXLは.NET Core、.NET Framework、Xamarin、Mobile、Linux、macOS、Azureなどの多様なプラットフォームをサポートしており、クロスプラットフォーム開発において非常に柔軟です。

IronXLを使用するためにサーバーやクライアントマシンにMicrosoft Officeをインストールする必要がありますか?

いいえ、IronXLはMicrosoft Officeのインストールを必要としません。Officeから独立して機能するように設計されており、Excelファイルの読み込み、編集、作成の機能を提供します。

Excelファイルを扱うためのEPPlusの主な機能は何ですか?

EPPlusはOffice OpenXMLのサポートで知られており、Excelに精通した開発者にとって使いやすく、ピボットテーブルの作成や条件付き書式の適用などの機能を備えています。商用および非商用の二重ライセンスモデルで提供されています。

私の.NETプロジェクトにIronXLをどのようにインストールできますか?

NuGetパッケージマネージャーコンソールでInstall-Package IronXL.Excelというコマンドを使用して、または.NET CLIを使用してdotnet add package IronXL.ExcelでIronXLをインストールできます。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。