C# で Excel ファイルを読み取る方法 (開発者向けチュートリアル)
このチュートリアルでは、C#でExcelファイルを読み取る方法や、データ検証、データベース変換、Web API統合、式の修正などの通常のタスクを実行する方法について説明します。 この記事では、IronXL .NET Excel ライブラリを利用したコード例を参照しています。
概要
How to Read Excel File in C#
- Excelファイルを読み取るためのC#ライブラリをダウンロード
- Excelファイル(ワークブック)を読み込んで読み取る
- CSVまたはXLSX形式でExcelワークブックを作成する
- セル範囲内のセル値を編集する
- スプレッドシートデータを検証する
- エンティティフレームワークを使用してデータをエクスポートします
IronXLは、C#を使用してMicrosoft Excelドキュメントの読み取りと編集を容易にします。 IronXLはMicrosoft Excelを必要とせず、Interopも必要としません。 実際、IronXLはMicrosoft.Office.Interop.Excel
よりも高速で直感的なAPIを提供します。
IronXL に含まれるもの:
- .NETエンジニアによる専用製品サポート
- Microsoft Visual Studioを介した簡単なインストール
-
開発用の無料試用テスト。 $749からのライセンス。
C#およびVB.NETでExcelファイルを読み書きすることは、IronXLソフトウェアライブラリを使用することにより容易になります。
IronXLを使用して.XLSおよび.XLSX Excelファイルを読み取る
以下は、IronXLを使用してExcelファイルを読み取るための全体的なワークフローの概要です:
-
IronXL Excelライブラリをインストールします。 これを行うには、NuGet パッケージを使用するか、.Net Excel DLLをダウンロードしてください。
-
WorkBook.Load
メソッドを使用して、XLS、XLSX、またはCSVドキュメントを読み取ります。 - 直感的な構文を使用してセルの値を取得します:
sheet ["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select cells easily in Excel notation and return the calculated value
int cellValue = workSheet["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Advanced Operations
// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();
// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Imports IronXL
Imports System
Imports System.Linq
' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = workSheet("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In workSheet("A2:A10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
' Advanced Operations
' Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = workSheet("A2:A10").Sum()
' Linq compatible
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
このチュートリアルの次のセクションで使用されるコード例(およびサンプルプロジェクトのコード)は、3つのサンプルExcelスプレッドシートで動作します(ビジュアルは以下を参照してください)。
チュートリアル
1. IronXL C#ライブラリを無料でダウンロード
今日から無料トライアルでIronXLをあなたのプロジェクトで使い始めましょう。
最初に行うべきことは、IronXL.Excel
ライブラリをインストールして、.NETフレームワークにExcel機能を追加することです。
IronXL.Excel
のインストールは、NuGet パッケージを使用するのが最も簡単です。ただし、DLL をプロジェクトまたはグローバル アセンブリ キャッシュに手動でインストールすることも選択できます。
IronXL NuGet パッケージのインストール
-
Visual Studioで、プロジェクトを右クリックして「NuGetパッケージの管理...」を選択します。
-
IronXL.Excelパッケージを検索し、インストールボタンをクリックしてプロジェクトに追加してください。
IronXLライブラリをインストールする別の方法は、NuGetパッケージマネージャーコンソールを使用することです。
-
パッケージマネージャーコンソールを入力してください
- タイプ
> Install-Package IronXL.Excel
PM > Install-Package IronXL.Excel
さらに、NuGetのウェブサイトでパッケージを表示することができます
手動インストール
または、IronXL .NET Excel DLLをダウンロードして、Visual Studio に手動でインストールすることもできます。
2. Excel ワークブックを読み込む
WorkBook
クラスはExcelシートを表します。 ExcelファイルをC#で開くには、Excelファイルのパスを指定してWorkBook.Load
メソッドを使用します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
WorkBook workBook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
サンプル: ExcelToDBProcessor
各WorkBook
には、複数のWorkSheet
オブジェクトを含めることができます。 それぞれは、Excelドキュメント内の単一のExcelワークシートを表します。 WorkBook.GetWorkSheet
メソッドを使用して、特定のExcelワークシートへの参照を取得します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs
サンプル:ExcelToDB
新しいExcelドキュメントの作成
新しいExcelドキュメントを作成するには、有効なファイルタイプを持つ新しいWorkBook
オブジェクトを構築します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
サンプル: ApiToExcelProcessor
注: レガシー版のMicrosoft Excel(95およびそれ以前)をサポートするには、ExcelFileFormat.XLS
を使用してください。
Excelドキュメントにワークシートを追加
前述のとおり、IronXLのWorkBook
には、1つ以上のWorkSheet
のコレクションが含まれています。
新しいWorkSheet
を作成するには、ワークシートの名前でWorkBook.CreateWorkSheet
を呼び出します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
セル値へのアクセス
単一のセルを読み取りおよび編集
個々のスプレッドシートセルの値へのアクセスは、WorkSheet
から目的のセルを取得することによって行われます。 以下に示すように:
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-16.cs
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Cell cell = workSheet["B1"].First();
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
Dim cell As IronXL.Cell = workSheet("B1").First()
IronXLのCell
クラスは、Excelスプレッドシートの個々のセルを表します。 それには、ユーザーがセルの値に直接アクセスし、修正することを可能にするプロパティとメソッドが含まれています。
各WorkSheet
オブジェクトは、Excelワークシート内のすべてのセル値に対応するCell
オブジェクトのインデックスを管理します。 上記のソースコードでは、標準的な配列インデックス構文を使用して、行と列のインデックス(この場合はセルB1)で目的のセルを参照しています。
セルオブジェクトへの参照を使うと、スプレッドシートのセルにデータを読み書きすることができます。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-17.cs
IronXL.Cell cell = workSheet["B1"].First();
string value = cell.StringValue; // Read the value of the cell as a string
Console.WriteLine(value);
cell.Value = "10.3289"; // Write a new value to the cell
Console.WriteLine(cell.StringValue);
Dim cell As IronXL.Cell = workSheet("B1").First()
Dim value As String = cell.StringValue ' Read the value of the cell as a string
Console.WriteLine(value)
cell.Value = "10.3289" ' Write a new value to the cell
Console.WriteLine(cell.StringValue)
セルの範囲の値を読み書きする
Range
クラスは、Cell
オブジェクトの2次元コレクションを表します。 このコレクションは、Excelセルのリテラル範囲を指します。 文字列インデクサーをWorkSheet
オブジェクトで使用して範囲を取得します。
引数のテキストは、セルの座標(例:「A1」、前に示したように)または左から右、上から下のセル範囲(例:「B2:E5」)です。 また、WorkSheet
でGetRange
を呼び出すことも可能です。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
Range range = workSheet["D2:D101"];
Dim range As Range = workSheet("D2:D101")
サンプル:DataValidation
範囲内のセルの値を読み取ったり編集したりするには、いくつかの方法があります。 カウントがわかっている場合は、For ループを使用してください。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// 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);
}
' 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
サンプル:DataValidation
スプレッドシートに数式を追加する
Cell
の数式は、Formula
プロパティで設定します。
以下のコードは各州を繰り返し処理し、列Cにパーセンテージの合計を入力します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-13.cs
// Iterate through all rows with a value
for (var y = 2 ; y < i ; y++)
{
// Get the C cell
Cell cell = workSheet[$"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 As Cell = workSheet($"C{y}").First()
' Set the formula for the Percentage of Total column
cell.Formula = $"=B{y}/B{i}"
y += 1
Loop
サンプル:AddFormulaeProcessor
スプレッドシートデータの検証
IronXLを使用してデータシートを検証します。 DataValidation
サンプルは、電話番号を検証するためにlibphonenumber-csharp
を使用し、メールアドレスと日付を検証するために標準のC# APIを使用します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
// 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);
}
' 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
上記のコードはスプレッドシート内の各行をループし、セルをリストとして取得します。各検証メソッドはセルの値をチェックし、その値が無効であればエラーメッセージを返します。
このコードは新しいシートを作成し、ヘッダーを指定し、不正データのログが取れるようにエラーメッセージの結果を出力します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
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")
エンティティフレームワークを使用してデータをエクスポートする
IronXLを使用して、データをデータベースにエクスポートしたり、Excelスプレッドシートをデータベースに変換したりできます。 ExcelToDB
サンプルは国別GDPを含むスプレッドシートを読み込み、そのデータをSQLiteにエクスポートします。
それはEntityFramework
を使用してデータベースを構築し、その後データを1行ずつエクスポートします。
SQLite エンティティ フレームワーク NuGet パッケージを追加します。
EntityFramework
は、データをデータベースにエクスポートできるモデルオブジェクトを作成可能にします。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-10.cs
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
別のデータベースを使用するには、対応するNuGetパッケージをインストールし、UseSqLite()
の同等のものを見つけてください。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-11.cs
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);
}
}
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
CountryContext
を作成し、範囲を反復処理して各レコードを作成し、その後データベースにデータをコミットするためにSaveAsync
を実行します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-12.cs
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
サンプル:ExcelToDB
APIからスプレッドシートへのデータダウンロード
次の呼び出しは、RestClient.Net を使用してRESTコールを行います。 それはJSONをダウンロードし、RestCountry
型の「List」に変換します。 次に、各国を繰り返し処理して、REST APIからのデータをExcelスプレッドシートに保存するのは簡単です。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-14.cs
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
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))()
サンプル: ApiToExcel
APIのJSONデータはこのように表示されます。
次のコードは、各国を順に処理し、スプレッドシートにName(名前)、Population(人口)、Region(地域)、NumericCode(数値コード)、およびTop 3 Languages(トップ3の言語)を設定します。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-15.cs
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
オブジェクトリファレンスとリソース
また、[IronXLクラスドキュメント](/csharp/excel/object-reference/api/" target="_blank)をオブジェクトリファレンス内で非常に価値のあるものと感じるかもしれません。
さらに、IronXL.Excel
の他の側面を明らかにするチュートリアルもあります。これには、作成、開く、書き込む、編集する、保存する、エクスポートする を含む、Excel Interop を使用しないで XLS、XLSX、CSV ファイルを操作する方法が含まれます。
サマリー
IronXL.Excelは、さまざまなスプレッドシート形式を読み取るための唯一の.NETソフトウェアライブラリです。 それをインストールするためにMicrosoft Excelを必要とせず、Interopに依存しません。
もし.NETライブラリがExcelファイルの修正に役立つと思うなら、Google Sheets API Client Library for .NETを探索して、Google Sheetsを修正することも考えてみてください。
チュートリアル クイック アクセス
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で探索する
The source code for this project is available in C# and VB.NET on GitHub.
このコードを使用すると、わずか数分で簡単に始められます。このプロジェクトはMicrosoft Visual Studio 2017プロジェクトとして保存されていますが、どの.NET IDEとも互換性があります。
How to Read Excel File in C# on GitHub