C#でExcelに書き込む [Interopを使用しない] コード例チュートリアル

.NET Excelライブラリは、データをウェブアプリケーションやビジネスシステムに取り込んだり、出力したりする方法を革命的に変えることができます。
イライジャ・ウィリアムズ
2019年5月26日
更新済み 2024年12月10日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English

C#を使用してExcelファイルを作成、開く、および保存する方法のステップバイステップの例に従い、合計、平均、カウントなどの基本的な操作を適用します。 IronXL.Excelは、さまざまなスプレッドシート形式を読み取るためのスタンドアロンの.NETソフトウェアライブラリです。 Microsoft Excelをインストールする必要がなく、Interopにも依存しません。


概要

IronXLを使用して、Excelファイルを開いて書き込みます。

Excelファイルを開く、書く、保存する、カスタマイズするのは、使いやすい[IronXL C#ライブラリ](/csharp/excel/" target="_blank)で可能です。

GitHubから[サンプルプロジェクトをダウンロード](https://github.com/magedo93/IronSoftware.git" target="_blank)するか、自作のものを使用し、チュートリアルに従ってください。

  1. [NuGet](https://www.nuget.org/packages/IronXL.Excel" target="_blank)またはDLLダウンロードからIronXL Excelライブラリをインストールします

  2. WorkBook.Loadメソッドを使用して、任意のXLS、XLSX、またはCSVドキュメントを読み込みます。

  3. 直感的な構文を使用してセルの値を取得します:sheet ["A11"].DecimalValue

    このチュートリアルでは、次の手順を説明します:

    • IronXL.Excelのインストール:既存のプロジェクトにIronXL.Excelをインストールする方法。
    • 基本操作: Excelでブックを作成または開くときの基本操作手順、シートの選択、セルの選択、ブックの保存
    • 高度なシート操作:ヘッダーまたはフッターの追加や数学的操作ファイル、その他の機能のようなさまざまな操作機能を活用する方法。

      Excelファイルを開く : クイックコード

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-1.cs
using IronXL;

WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Range range = workSheet["A2:A8"];
decimal total = 0;

// iterate over range of cells
foreach (var cell in range)
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value);
    if (cell.IsNumeric)
    {
        // Get decimal value to avoid floating numbers precision issue
        total += cell.DecimalValue;
    }
}

// Check formula evaluation
if (workSheet["A11"].DecimalValue == total)
{
    Console.WriteLine("Basic Test Passed");
}
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet
Private range As IronXL.Range = workSheet("A2:A8")
Private total As Decimal = 0

' iterate over range of cells
For Each cell In range
	Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value)
	If cell.IsNumeric Then
		' Get decimal value to avoid floating numbers precision issue
		total += cell.DecimalValue
	End If
Next cell

' Check formula evaluation
If workSheet("A11").DecimalValue = total Then
	Console.WriteLine("Basic Test Passed")
End If
$vbLabelText   $csharpLabel

Excelファイルに変更を書き込み保存:クイックコード

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-2.cs
workSheet["B1"].Value = 11.54;

// Save Changes
workBook.SaveAs("test.xlsx");
workSheet("B1").Value = 11.54

' Save Changes
workBook.SaveAs("test.xlsx")
$vbLabelText   $csharpLabel

ステップ 1

1. IronXL C# ライブラリを無料でインストールする

今日から無料トライアルでIronXLをあなたのプロジェクトで使い始めましょう。

最初のステップ:
green arrow pointer


IronXL.Excelは、.NETでExcelファイルを開き、読み取り、編集、保存するための柔軟かつ強力なライブラリを提供します。 それは、WindowsアプリケーションやASP.NET MVC、.NET Coreアプリケーションなど、すべての.NETプロジェクトタイプにインストールして使用できます。

NuGetを使用してExcelライブラリをVisual Studioプロジェクトにインストールする

最初のステップはIronXL.Excelをインストールすることです。 プロジェクトにIronXL.Excelライブラリを追加するには、2つの方法があります: NuGetパッケージマネージャーまたはNuGetパッケージマネージャーコンソール。

プロジェクトにIronXL.ExcelライブラリをNuGetを使用して追加するには、可視化されたインターフェースであるNuGetパッケージマネージャを使用して行うことができます。

  1. マウスを使用して -> プロジェクトの名前を右クリック -> 「NuGet パッケージの管理」を選択

    Select Manage Nuget Package related to NuGetを使用してExcelライブラリをVisual Studioプロジェクトにイ...

  2. 参照タブから -> IronXL.Excelを検索 -> インストール

    Search For Ironxl related to NuGetを使用してExcelライブラリをVisual Studioプロジェクトにインスト...

  3. 完了しました。

    And We Are Done related to NuGetを使用してExcelライブラリをVisual Studioプロジェクトにインストー...

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

  4. ツール -> NuGetパッケージマネージャー -> パッケージマネージャーコンソールから

    Package Manager Console related to NuGetを使用してExcelライブラリをVisual Studioプロジェクトにイン...

  5. 実行コマンド -> Install-Package IronXL.Excel -Version 2019.5.2

    Install Package Ironxl related to NuGetを使用してExcelライブラリをVisual Studioプロジェクトにインス...

    DLLを使用して手動インストール

    また、DLL をプロジェクトまたはグローバル アセンブリ キャッシュに手動でインストールすることもできます。 ```

PM > Install-Package IronXL.Excel

<hr class="separator">
<h4 class="tutorial-segment-title">チュートリアルの方法</h4>

## 2. 基本操作:作成、開く、保存

### 2.1. サンプルプロジェクト:HelloWorld コンソールアプリケーション &num;&num;&num;

<p class="list-description">HelloWorldプロジェクトを作成</p>
<p class="list-decimal">2.1.1. Visual Studioを開く</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/open-visual-studio.png" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/open-visual-studio.png" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">2.1.2. 新しいプロジェクトを作成を選択</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/choose-create-new-project.png" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/choose-create-new-project.png" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">2.1.3. コンソール アプリ (.NET フレームワーク) を選択</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/choose-console-app.jpg" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/choose-console-app.jpg" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">サンプルに「HelloWorld」という名前を付けて、作成をクリックします。</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/give-our-sample-name.jpg" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/give-our-sample-name.jpg" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">2.1.5. これでコンソールアプリケーションが作成されました</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/console-application-created.jpg" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/console-application-created.jpg" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">2.1.6. Add IronXL.Excel => click install</p>
<a rel="nofollow" href="/img/tutorials/csharp-open-write-excel-file/add-ironxl-click-install.jpg" target="_blank"><img src="/img/tutorials/csharp-open-write-excel-file/add-ironxl-click-install.jpg" alt="" class="img-responsive add-shadow img-margin" style="max-width:100%;"></a>
<p class="list-decimal">2.1.7. Excelファイルの最初のシートの最初のセルを読み込み、印刷するための最初の数行を追加します。</p>

```cs
:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-3.cs

2.2. 新しいExcelファイルを作成する ###

IronXLを使用して新しいExcelファイルを作成する

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-4.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";
WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed
$vbLabelText   $csharpLabel

2.3. (CSV、XML、JSONリスト)をブックとして開く

2.3.1. CSVファイルを開く

新しいテキストファイルを作成し、名前と年齢のリストを追加してください(例を参照)。それを CSVList.csv として保存します。

Code Snippet related to 2.3. (CSV、XML、JSONリスト)をブックとして開く

あなたのコードスニペットはこのように見えるべきです

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-5.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\CSVList.csv");
WorkSheet workSheet = workBook.WorkSheets.First();
string cell = workSheet["A1"].StringValue;
Console.WriteLine(cell);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\CSVList.csv")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim cell As String = workSheet("A1").StringValue
Console.WriteLine(cell)
$vbLabelText   $csharpLabel

2.3.3. Open XML File Create an XML file that contains a countries list: the root element “countries”, with children elements “country”, and each country has properties that define the country like code, continent, etc.

<?xml version="1.0" encoding="utf-8"?>
<countries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <country code="ae" handle="united-arab-emirates" continent="asia" iso="784">United Arab Emirates</country>
        <country code="gb" handle="united-kingdom" continent="europe" alt="England Scotland Wales GB UK Great Britain Britain Northern" boost="3" iso="826">United Kingdom</country>
        <country code="us" handle="united-states" continent="north america" alt="US America USA" boost="2" iso="840">United States</country>
        <country code="um" handle="united-states-minor-outlying-islands" continent="north america" iso="581">United States Minor Outlying Islands</country>
</countries>
<?xml version="1.0" encoding="utf-8"?>
<countries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <country code="ae" handle="united-arab-emirates" continent="asia" iso="784">United Arab Emirates</country>
        <country code="gb" handle="united-kingdom" continent="europe" alt="England Scotland Wales GB UK Great Britain Britain Northern" boost="3" iso="826">United Kingdom</country>
        <country code="us" handle="united-states" continent="north america" alt="US America USA" boost="2" iso="840">United States</country>
        <country code="um" handle="united-states-minor-outlying-islands" continent="north america" iso="581">United States Minor Outlying Islands</country>
</countries>
HTML

以下のコードスニペットをコピーして、XMLをワークブックとして開きます

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-7.cs
DataSet xmldataset = new DataSet();
xmldataset.ReadXml($@"{Directory.GetCurrentDirectory()}\Files\CountryList.xml");
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim xmldataset As New DataSet()
xmldataset.ReadXml($"{Directory.GetCurrentDirectory()}\Files\CountryList.xml")
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
$vbLabelText   $csharpLabel

2.3.5. Open JSON List as workbook Create JSON country list

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-8.cs
[
    {
        "name": "United Arab Emirates",
        "code": "AE"
    },
    {
        "name": "United Kingdom",
        "code": "GB"
    },
    {
        "name": "United States",
        "code": "US"
    },
    {
        "name": "United States Minor Outlying Islands",
        "code": "UM"
    }
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[{ "name": "United Arab Emirates", "code": "AE" }, { "name": "United Kingdom", "code": "GB" }, { "name": "United States", "code": "US" }, { "name": "United States Minor Outlying Islands", "code": "UM" }]
$vbLabelText   $csharpLabel

2.3.6. JSONにマッピングする国モデルを作成する

Create Country Model related to 2.3. (CSV、XML、JSONリスト)をブックとして開く

以下はクラスコードスニペットです

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-9.cs
public class CountryModel
    {
        public string name { get; set; }
        public string code { get; set; }
    }
Public Class CountryModel
		Public Property name() As String
		Public Property code() As String
End Class
$vbLabelText   $csharpLabel

2.3.8. JSONを国モデルのリストに変換するためにNewtonsoftライブラリを追加する

Add Newtonsoft Library To Convert Json related to 2.3. (CSV、XML、JSONリスト)をブックとして開く

2.3.9 リストをデータセットに変換するには、リストの新しい拡張機能を作成する必要があります。「ListConvertExtension」という名前の拡張クラスを追加します。

Convert List To Dataset related to 2.3. (CSV、XML、JSONリスト)をブックとして開く

次に、このコードスニペットを追加してください

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-10.cs
public static class ListConvertExtension
    {
        public static DataSet ToDataSet<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);
            //add a column to table for each public property on T
            foreach (var propInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
                t.Columns.Add(propInfo.Name, ColType);
            }
            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();
                foreach (var propInfo in elementType.GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                }
                t.Rows.Add(row);
            }
            return ds;
        }
    }
Public Module ListConvertExtension
		<System.Runtime.CompilerServices.Extension> _
		Public Function ToDataSet(Of T)(ByVal list As IList(Of T)) As DataSet
			Dim elementType As Type = GetType(T)
			Dim ds As New DataSet()
'INSTANT VB NOTE: The variable t was renamed since Visual Basic does not allow local variables with the same name as method-level generic type parameters:
			Dim t_Conflict As New DataTable()
			ds.Tables.Add(t_Conflict)
			'add a column to table for each public property on T
			For Each propInfo In elementType.GetProperties()
				Dim ColType As Type = If(Nullable.GetUnderlyingType(propInfo.PropertyType), propInfo.PropertyType)
				t_Conflict.Columns.Add(propInfo.Name, ColType)
			Next propInfo
			'go through each property on T and add each value to the table
			For Each item As T In list
				Dim row As DataRow = t_Conflict.NewRow()
				For Each propInfo In elementType.GetProperties()
					row(propInfo.Name) = If(propInfo.GetValue(item, Nothing), DBNull.Value)
				Next propInfo
				t_Conflict.Rows.Add(row)
			Next item
			Return ds
		End Function
End Module
$vbLabelText   $csharpLabel

そして最後に、このデータセットをワークブックとして読み込みます。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-11.cs
StreamReader jsonFile = new StreamReader($@"{Directory.GetCurrentDirectory()}\Files\CountriesList.json");
var countryList = Newtonsoft.Json.JsonConvert.DeserializeObject<CountryModel[]>(jsonFile.ReadToEnd());
var xmldataset = countryList.ToDataSet();
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim jsonFile As New StreamReader($"{Directory.GetCurrentDirectory()}\Files\CountriesList.json")
Dim countryList = Newtonsoft.Json.JsonConvert.DeserializeObject(Of CountryModel())(jsonFile.ReadToEnd())
Dim xmldataset = countryList.ToDataSet()
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
$vbLabelText   $csharpLabel

2.4. 保存とエクスポート ###

以下のコマンドのいずれかを使用して、Excelファイルを複数のファイル形式(「.xlsx」、「.csv」、「.html」)に保存またはエクスポートできます。

2.4.1. 「.xlsx」に保存する 「.xlsx」に保存するには、saveAs関数を使用します

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-12.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";

WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;

workBook.SaveAs($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"

Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed

workBook.SaveAs($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx")
$vbLabelText   $csharpLabel

2.4.2. Save to csv “.csv” To save to “.csv” we can use SaveAsCsv and pass to it 2 parameters 1st parameter the file name and path the 2nd parameter is the delimiter like (“,” or “” or “:”)

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-13.cs
workBook.SaveAsCsv($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.csv", delimiter: "|");
workBook.SaveAsCsv($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.csv", delimiter:= "|")
$vbLabelText   $csharpLabel

2.4.3. Save to JSON “.json” To save to Json “.json” use SaveAsJson as follow

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-14.cs
workBook.SaveAsJson($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldJSON.json");
workBook.SaveAsJson($"{Directory.GetCurrentDirectory()}\Files\HelloWorldJSON.json")
$vbLabelText   $csharpLabel

結果ファイルはこのように見えるはずです

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-15.cs
[
    [
        "Hello World"
    ],
    [
        ""
    ]
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[["Hello World"], [""]]
$vbLabelText   $csharpLabel

2.4.4. XML “.xml” への保存 XMLに保存するには、次のように SaveAsXml を使用します

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-16.cs
workBook.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
workBook.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>
HTML

3. 高度な操作: 合計、平均、カウントなど

一般的なExcel関数(SUM、AVG、Countなど)を適用し、それぞれのコードスニペットを見てみましょう。

3.1. 合計の例 ###

このリストの合計を求めましょう。Excelファイルを作成し、「Sum.xlsx」と名付けて手動でこの数字のリストを追加しました。

Sum Example related to 3.1. 合計の例 ###

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-18.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal sum = workSheet["A2:A4"].Sum();
Console.WriteLine(sum);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim sum As Decimal = workSheet("A2:A4").Sum()
Console.WriteLine(sum)
$vbLabelText   $csharpLabel

3.2. Avg Example ###

同じファイルを使用して、平均を取得できます:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-19.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal avg = workSheet["A2:A4"].Avg();
Console.WriteLine(avg);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim avg As Decimal = workSheet("A2:A4").Avg()
Console.WriteLine(avg)
$vbLabelText   $csharpLabel

3.3. カウントの例 ###

同じファイルを使用して、シーケンス内の要素数を取得することもできます。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-20.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal count = workSheet["A2:A4"].Count();
Console.WriteLine(count);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim count As Decimal = workSheet("A2:A4").Count()
Console.WriteLine(count)
$vbLabelText   $csharpLabel

3.4. 最大例 ###

同じファイルを使用して、セル範囲の最大値を取得できます:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-21.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal max = workSheet["A2:A4"].Max();
Console.WriteLine(max);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max As Decimal = workSheet("A2:A4").Max()
Console.WriteLine(max)
$vbLabelText   $csharpLabel

– max関数の結果にtransform関数を適用することができます:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-22.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
bool max2 = workSheet["A1:A4"].Max(c => c.IsFormula);
Console.WriteLine(max2);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max2 As Boolean = workSheet("A1:A4").Max(Function(c) c.IsFormula)
Console.WriteLine(max2)
$vbLabelText   $csharpLabel

この例では、コンソールに「false」と出力します。

3.5. Min Example ###

同じファイルを使用して、セル範囲の最小値を取得することができます。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-23.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal min = workSheet["A1:A4"].Min();
Console.WriteLine(min);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim min As Decimal = workSheet("A1:A4").Min()
Console.WriteLine(min)
$vbLabelText   $csharpLabel

3.6. セルを並べ替える例 ###

同じファイルを使用して、セルを昇順または降順に並べ替えることができます。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-24.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
workSheet["A1:A4"].SortAscending();
// workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
workSheet("A1:A4").SortAscending()
' workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx")
$vbLabelText   $csharpLabel

3.7. If条件の例

同じファイルを使用して、Formulaプロパティを使ってセルの数式を設定または取得することができます:

3.7.1. XML「.xml」形式で保存

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-25.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["B1:B4"])
{
    cell.Formula = "=IF(A" + i + ">=20,\" Pass\" ,\" Fail\" )";
    i++;
}
workBook.SaveAs($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("B1:B4")
	cell.Formula = "=IF(A" & i & ">=20,"" Pass"" ,"" Fail"" )"
	i += 1
Next cell
workBook.SaveAs($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
$vbLabelText   $csharpLabel

7.2. 前の例で生成されたファイルを使用して、セルの数式を取得できます:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-26.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
foreach (var cell in workSheet["B1:B4"])
{
    Console.WriteLine(cell.Formula);
}
Console.ReadKey();
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
For Each cell In workSheet("B1:B4")
	Console.WriteLine(cell.Formula)
Next cell
Console.ReadKey()
$vbLabelText   $csharpLabel

3.8. トリム例 ###

セル内の余分なスペースをすべて削除するtrim関数を適用するため、この列をsum.xlsxファイルに追加しました。

Trim Example related to 3.8. トリム例 ###

このコードを使用して

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-27.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["f1:f4"])
{
    cell.Formula = "=trim(D" + i + ")";
    i++;
}
workBook.SaveAs("editedFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("f1:f4")
	cell.Formula = "=trim(D" & i & ")"
	i += 1
Next cell
workBook.SaveAs("editedFile.xlsx")
$vbLabelText   $csharpLabel

したがって、同じ方法で数式を適用することができます。


4. マルチシートワークブックを操作する ##

複数のシートを持つワークブックの操作方法について説明します。

4.1. 同じワークブック内の複数のシートからデータを読み取る ###

次のような内容のxlsxファイルを作成しました。2つのシートが含まれています:「Sheet1」、「Sheet2」

これまでは WorkSheets.First() を使用して最初のシートを操作していました。この例ではシート名を指定してそのシートを操作します。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-28.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet workSheet = workBook.GetWorkSheet("Sheet2");
var range = workSheet["A2:D2"];
foreach (var cell in range)
{
    Console.WriteLine(cell.Text);
}
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet2")
Dim range = workSheet("A2:D2")
For Each cell In range
	Console.WriteLine(cell.Text)
Next cell
$vbLabelText   $csharpLabel

4.2. 新しいシートをワークブックに追加 ###

ワークブックに新しいシートを追加することもできます:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-29.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");
workSheet["A1"].Value = "Hello World";
workBook.SaveAs(@"F:\MY WORK\IronPackage\Xl tutorial\newFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("new_sheet")
workSheet("A1").Value = "Hello World"
workBook.SaveAs("F:\MY WORK\IronPackage\Xl tutorial\newFile.xlsx")
$vbLabelText   $csharpLabel

5. Excelデータベースと統合

データベースにデータをエクスポート/インポートする方法を見てみましょう。

"TestDb"データベースを作成し、2つの列を持つCountryテーブル(Id(int、identity)、CountryName(string))を含めました。

5.1. データベースからデータを取得してExcelシートを埋める ###

ここでは、新しいシートを作成し、Country Tableからのデータで埋めます。

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-30.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet sheet = workbook.CreateWorkSheet("FromDb");
List<Country> countryList = dbContext.Countries.ToList();
sheet.SetCellValue(0, 0, "Id");
sheet.SetCellValue(0, 1, "Country Name");
int row = 1;
foreach (var item in countryList)
{
    sheet.SetCellValue(row, 0, item.id);
    sheet.SetCellValue(row, 1, item.CountryName);
    row++;
}
workbook.SaveAs("FilledFile.xlsx");
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim sheet As WorkSheet = workbook.CreateWorkSheet("FromDb")
Dim countryList As List(Of Country) = dbContext.Countries.ToList()
sheet.SetCellValue(0, 0, "Id")
sheet.SetCellValue(0, 1, "Country Name")
Dim row As Integer = 1
For Each item In countryList
	sheet.SetCellValue(row, 0, item.id)
	sheet.SetCellValue(row, 1, item.CountryName)
	row += 1
Next item
workbook.SaveAs("FilledFile.xlsx")
$vbLabelText   $csharpLabel

5.2. Excelシートからデータベースにデータを入力 ###

TestDbデータベースのCountryテーブルにデータを挿入する

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-31.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet3");
System.Data.DataTable dataTable = sheet.ToDataTable(true);
foreach (DataRow row in dataTable.Rows)
{
    Country c = new Country();
    c.CountryName = row[1].ToString();
    dbContext.Countries.Add(c);
}
dbContext.SaveChanges();
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet3")
Dim dataTable As System.Data.DataTable = sheet.ToDataTable(True)
For Each row As DataRow In dataTable.Rows
	Dim c As New Country()
	c.CountryName = row(1).ToString()
	dbContext.Countries.Add(c)
Next row
dbContext.SaveChanges()
$vbLabelText   $csharpLabel

さらに読む

IronXLの使用方法について詳しく知りたい場合は、このセクション内の他のチュートリアルや、ほとんどの開発者が始めるのに十分な例が見つかる私たちのホームページの例を参照することをお勧めします。

私たちのAPIリファレンスには、WorkBookクラスへの特定のリファレンスが含まれています。


チュートリアル クイック アクセス

Brand Visual Studio related to チュートリアル クイック アクセス

Download this Tutorial as C# Source Code

The full free C# for Excel Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download

このチュートリアルをGitHubで探索する

このプロジェクトのソースコードはGitHubでC#およびVB.NETで利用可能です。

このコードを使用すると、わずか数分で簡単に始められます。このプロジェクトはMicrosoft Visual Studio 2017プロジェクトとして保存されていますが、どの.NET IDEとも互換性があります。

GitHubでC#を使用してExcelファイルを開き、書き込む方法
Github Icon related to チュートリアル クイック アクセス
Documentation related to チュートリアル クイック アクセス

IronXLのAPIリファレンス

Explore the IronXLのAPIリファレンス, outlining the details of all of IronXL’s features, namespaces, classes, methods fields and enums.

APIリファレンスを表示
.NET Excelライブラリは、データをウェブアプリケーションやビジネスシステムに取り込んだり、出力したりする方法を革命的に変えることができます。
プロダクト開発エンジニア

Elijahは、大規模な企業財務報告システムを担当する開発およびテストチームのエンジニアです。Elijahは、ExcelレポートインターフェースのコアにIronXLライブラリを取り入れた初期の導入者です。