IronXL チュートリアル C# で Excel ファイルを読み取る方法 C#でExcelファイルを読む方法:完全な開発者ガイド Jacob Mellor 更新日:2026年1月31日 IronXL をダウンロード NuGet ダウンロード DLL ダウンロード 無料トライアル LLM向けのコピー LLM向けのコピー LLM 用の Markdown としてページをコピーする ChatGPTで開く このページについてChatGPTに質問する ジェミニで開く このページについてGeminiに問い合わせる Grokで開く このページについてGrokに質問する 困惑の中で開く このページについてPerplexityに問い合わせる 共有する Facebook で共有 Xでシェア(Twitter) LinkedIn で共有 URLをコピー 記事をメールで送る This article was translated from English: Does it need improvement? Translated View the article in English IronXLを使用してC#でExcelファイルを操作する方法を習得します。Microsoft Officeのインストールを必要とせず、スプレッドシートデータを読み込み、検証し、エクスポートできる強力な.NETライブラリです。 この包括的なチュートリアルは、データ検証、データベース変換、およびREST API統合を含む実践的なExcel操作を示しています。 クイックスタート:IronXLで1行でセルを読み取る IronXLを使用して1行でExcelワークブックをロードし、セルの値を取得できます。 複雑なセットアップは不要、Interopも不要で迅速にデータにアクセスできます。 IronXL をNuGetパッケージマネージャでインストール PM > Install-Package IronXL.Excel このコード スニペットをコピーして実行します。 var value = IronXL.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue; 実際の環境でテストするためにデプロイする 今日プロジェクトで IronXL を使い始めましょう無料トライアル Free 30 Day Trial C#でIronXL.Excelファイルを読み込むにはどうすればよいですか? C#プロジェクトでExcelファイルを読み込むためのIronXLの設定は数分で完了します。 ライブラリは.XLSと.XLSXフォーマットの両方をサポートしているため、あらゆるExcel関連のタスクに対応しています。 開始するには、以下の手順に従ってください: C#ライブラリをダウンロードしてExcelファイルを読み込みます WorkBook.Load()を使用してExcelワークブックをロードして読み取ります GetWorkSheet()メソッドを使用してワークシートにアクセスします sheet["A1"].Valueのような直感的な構文を使用してセルの値を読み取ります プログラムでスプレッドシートデータを検証および処理します エンティティフレームワークを使用してデータをデータベースにエクスポートします IronXLは、C#でMicrosoft Excelドキュメントを読み取りおよび編集するのに優れています。 ライブラリは独立して動作し、Microsoft ExcelやInteropを必要としません。 実際に、IronXLはMicrosoft.Office.Interop.Excelよりも高速で直感的なAPIを提供します。 IronXLには以下が含まれます: .NETエンジニアによる専用の製品サポート Microsoft Visual Studioを介した簡単なインストール 開発用の無料試用版。 liteLicenseからのライセンス IronXLソフトウェアライブラリを使用すると、C#およびVB.NETでのExcelファイルの読み取りおよび作成が簡単になります。 IronXLを使用して.XLSおよび.XLSX Excelファイルを読み取る IronXLを使用してExcelファイルを読み取る基本的なワークフローは次のとおりです: NuGetパッケージを介してIronXL Excelライブラリをインストールするか、.NET Excel DLLをダウンロードします。 任意のXLS、XLSX、またはCSV文書を読み取るためにWorkBook.Load()メソッドを使用します 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; // Load Excel workbook from file path WorkBook workBook = WorkBook.Load("test.xlsx"); // Access the first worksheet using LINQ WorkSheet workSheet = workBook.WorkSheets.First(); // Read integer value from cell A2 int cellValue = workSheet["A2"].IntValue; Console.WriteLine($"Cell A2 value: {cellValue}"); // Iterate through a range of cells foreach (var cell in workSheet["A2:A10"]) { Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text); } // Advanced Operations with LINQ // Calculate sum using built_in Sum() method decimal sum = workSheet["A2:A10"].Sum(); // Find maximum value using LINQ decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue); // Output calculated results Console.WriteLine($"Sum of A2:A10: {sum}"); Console.WriteLine($"Maximum value: {max}"); $vbLabelText $csharpLabel このコードは、IronXLのいくつかの主要な機能、ワークブックのロード、アドレスによるセルへのアクセス、範囲の反復、および計算の実行を示しています。 WorkBook.Load()メソッドはファイルフォーマットを賢く検出し、範囲構文["A2:A10"]はExcelライクなセル選択を提供します。 LINQの統合により、セルコレクションへの強力なデータクエリと集計が可能になります。 このチュートリアルのコード例は、さまざまなデータシナリオを紹介する3つのサンプルExcelスプレッドシートで動作します: このチュートリアルで使用されるサンプルExcelファイル(GDP.xlsx、People.xlsx、PopulationByState.xlsx)は、さまざまなIronXL操作を示します。 IronXL C#ライブラリをインストールするにはどうすればいいですか? IronXL.Excelライブラリをインストールすると、.NETフレームワークプロジェクトに包括的なExcel機能が追加されます。 NuGetインストールまたは手動DLL統合から選択できます。 IronXL NuGetパッケージのインストール Visual Studioで、プロジェクトを右クリックし、"NuGetパッケージの管理"を選択します。 "参照"タブで"IronXL.Excel"を検索します。 インストールボタンをクリックして、IronXLをプロジェクトに追加します Visual StudioのNuGetパッケージマネージャーを通じてIronXLをインストールすることにより、自動的な依存関係の管理を提供します。 または、パッケージマネージャーコンソールを使用してIronXLをインストールします: パッケージマネージャーコンソールを開く(ツール → NuGetパッケージマネージャー → パッケージマネージャーコンソール) インストールコマンドを実行します: Install-Package IronXL.Excel また、NuGet Webサイトでパッケージ詳細を確認することもできます。 手動インストール 手動インストールでは、IronXLの.NET Excel DLLをダウンロードし、Visual Studioプロジェクトに直接参照として追加します。 Excelワークブックを読み込んで読み取るにはどうすればいいですか? WorkBookクラスはExcelファイル全体を表します。WorkBook.Load()メソッドを使用してExcelファイルをロードします。このメソッドは、XLS、XLSX、CSV、およびTSVフォーマットのファイルパスを受け入れます。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs using IronXL; using System; using System.Linq; // Load Excel file from specified path WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx"); Console.WriteLine("Workbook loaded successfully."); // Access specific worksheet by name WorkSheet sheet = workBook.GetWorkSheet("Sheet1"); // Read and display cell value string cellValue = sheet["A1"].StringValue; Console.WriteLine($"Cell A1 contains: {cellValue}"); // Perform additional operations // Count non_empty cells in column A int rowCount = sheet["A:A"].Count(cell => !cell.IsEmpty); Console.WriteLine($"Column A has {rowCount} non_empty cells"); $vbLabelText $csharpLabel 各WorkBookには、個別のExcelシートを表す複数のWorkSheetオブジェクトが含まれています。 GetWorkSheet()を使用して、名前でワークシートにアクセスします: :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs using IronXL; using System; // Get worksheet by name WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry"); Console.WriteLine("Worksheet 'GDPByCountry' not found"); // List available worksheets foreach (var sheet in workBook.WorkSheets) { Console.WriteLine($"Available: {sheet.Name}"); } $vbLabelText $csharpLabel C#で新しい Excel ドキュメントを作成するにはどうすればよいですか? お好みのファイルフォーマットでWorkBookオブジェクトを構築することで、新しいExcelドキュメントを作成します。 IronXLは、最新のXLSXフォーマットと旧式のXLSフォーマットの両方をサポートしています。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs using IronXL; // Create new XLSX workbook (recommended format) WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX); // Set workbook metadata workBook.Metadata.Author = "Your Application"; workBook.Metadata.Comments = "Generated by IronXL"; // Create new XLS workbook for legacy support WorkBook legacyWorkBook = WorkBook.Create(ExcelFileFormat.XLS); // Save the workbook workBook.SaveAs("NewDocument.xlsx"); $vbLabelText $csharpLabel 注意: ExcelFileFormat.XLSは、Excel 2003およびそれ以前との互換性が必要な場合にのみ使用してください。 Excelドキュメントにワークシートを追加するにはどうすればいいですか? IronXLのWorkBookは、ワークシートのコレクションを含んでいます。 この構造を理解することで、複数シートのExcelファイルを構築する際に役立ちます。 IronXLの複数のWorkSheetオブジェクトを含むWorkBookの視覚的表現。 CreateWorkSheet()を使用して新しいワークシートを作成します: :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs using IronXL; // Create multiple worksheets with descriptive names WorkSheet summarySheet = workBook.CreateWorkSheet("Summary"); WorkSheet dataSheet = workBook.CreateWorkSheet("RawData"); WorkSheet chartSheet = workBook.CreateWorkSheet("Charts"); // Set the active worksheet workBook.SetActiveTab(0); // Makes "Summary" the active sheet // Access default worksheet (first sheet) WorkSheet defaultSheet = workBook.DefaultWorkSheet; $vbLabelText $csharpLabel セルの値を読み取って編集するにはどうすればいいですか? 単一のセルを読み取って編集する ワークシートのインデクサープロパティを通じて個々のセルにアクセスします。 IronXLのCellクラスは、強く型付けされた値プロパティを提供します。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs using IronXL; using System; using System.Linq; // Load workbook and get worksheet WorkBook workBook = WorkBook.Load("test.xlsx"); WorkSheet workSheet = workBook.DefaultWorkSheet; // Access cell B1 IronXL.Cell cell = workSheet["B1"].First(); // Read cell value with type safety string textValue = cell.StringValue; int intValue = cell.IntValue; decimal decimalValue = cell.DecimalValue; DateTime? dateValue = cell.DateTimeValue; // Check cell data type if (cell.IsNumeric) { Console.WriteLine($"Numeric value: {cell.DecimalValue}"); } else if (cell.IsText) { Console.WriteLine($"Text value: {cell.StringValue}"); } $vbLabelText $csharpLabel Cellクラスは、可能な場合に自動的に値を変換する複数のプロパティを提供します。 セルの操作の詳細については、セルのフォーマットチュートリアルを参照してください。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs // Write different data types to cells workSheet["A1"].Value = "Product Name"; // String workSheet["B1"].Value = 99.95m; // Decimal workSheet["C1"].Value = DateTime.Today; // Date workSheet["D1"].Formula = "=B1*1.2"; // Formula // Format cells workSheet["B1"].FormatString = "$#,##0.00"; // Currency format workSheet["C1"].FormatString = "yyyy-MM-dd";// Date format // Save changes workBook.Save(); $vbLabelText $csharpLabel セル範囲を操作するにはどうすればいいですか? IronXLのRangeクラスは、複数のセルを表し、Excelデータに対する一括操作を可能にします。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs using IronXL; using Range = IronXL.Range; // Select range using Excel notation Range range = workSheet["D2:D101"]; // Alternative: Use Range class for dynamic selection Range dynamicRange = workSheet.GetRange("D2:D101"); // Row 2_101, Column D // Perform bulk operations range.Value = 0; // Set all cells to 0 $vbLabelText $csharpLabel セルの数がわかっている場合は、ループを使用して効率的に範囲を処理します: // Data validation example public class ValidationResult { public int Row { get; set; } public string PhoneError { get; set; } public string EmailError { get; set; } public string DateError { get; set; } public bool IsValid => string.IsNullOrEmpty(PhoneError) && string.IsNullOrEmpty(EmailError) && string.IsNullOrEmpty(DateError); } // Validate data in rows 2-101 var results = new List<ValidationResult>(); for (int row = 2; row <= 101; row++) { var result = new ValidationResult { Row = row }; // Get row data efficiently var phoneCell = workSheet[$"B{row}"]; var emailCell = workSheet[$"D{row}"]; var dateCell = workSheet[$"E{row}"]; // Validate phone number if (!IsValidPhoneNumber(phoneCell.StringValue)) result.PhoneError = "Invalid phone format"; // Validate email if (!IsValidEmail(emailCell.StringValue)) result.EmailError = "Invalid email format"; // Validate date if (!dateCell.IsDateTime) result.DateError = "Invalid date format"; results.Add(result); } // Helper methods bool IsValidPhoneNumber(string phone) => System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$"); bool IsValidEmail(string email) => email.Contains("@") && email.Contains("."); // Data validation example public class ValidationResult { public int Row { get; set; } public string PhoneError { get; set; } public string EmailError { get; set; } public string DateError { get; set; } public bool IsValid => string.IsNullOrEmpty(PhoneError) && string.IsNullOrEmpty(EmailError) && string.IsNullOrEmpty(DateError); } // Validate data in rows 2-101 var results = new List<ValidationResult>(); for (int row = 2; row <= 101; row++) { var result = new ValidationResult { Row = row }; // Get row data efficiently var phoneCell = workSheet[$"B{row}"]; var emailCell = workSheet[$"D{row}"]; var dateCell = workSheet[$"E{row}"]; // Validate phone number if (!IsValidPhoneNumber(phoneCell.StringValue)) result.PhoneError = "Invalid phone format"; // Validate email if (!IsValidEmail(emailCell.StringValue)) result.EmailError = "Invalid email format"; // Validate date if (!dateCell.IsDateTime) result.DateError = "Invalid date format"; results.Add(result); } // Helper methods bool IsValidPhoneNumber(string phone) => System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$"); bool IsValidEmail(string email) => email.Contains("@") && email.Contains("."); $vbLabelText $csharpLabel Excelスプレッドシートに数式を追加するにはどうすればいいですか? Formulaプロパティを使用してExcelの数式を適用します。 IronXLは、標準のExcel数式構文をサポートしています。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs using IronXL; // Add formulas to calculate percentages int lastRow = 50; for (int row = 2; row < lastRow; row++) { // Calculate percentage: current value / total workSheet[$"C{row}"].Formula = $"=B{row}/B{lastRow}"; // Format as percentage workSheet[$"C{row}"].FormatString = "0.00%"; } // Add summary formulas workSheet["B52"].Formula = "=SUM(B2:B50)"; // Sum workSheet["B53"].Formula = "=AVERAGE(B2:B50)"; // Average workSheet["B54"].Formula = "=MAX(B2:B50)"; // Maximum workSheet["B55"].Formula = "=MIN(B2:B50)"; // Minimum // Force formula evaluation workBook.EvaluateAll(); $vbLabelText $csharpLabel 既存の数式を編集するには、Excel数式チュートリアルを探索してください。 スプレッドシートデータを検証するにはどうすればいいですか? IronXLはスプレッドシートの包括的なデータ検証を可能にします。 この例は、電話番号、メール、および日付を外部ライブラリと組み込みのC#機能を使用して検証します。 using System.Text.RegularExpressions; using IronXL; // Validation implementation for (int i = 2; i <= 101; i++) { var result = new PersonValidationResult { Row = i }; results.Add(result); // Get cells for current person var cells = workSheet[$"A{i}:E{i}"].ToList(); // Validate phone (column B) string phone = cells[1].StringValue; if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$")) { result.PhoneNumberErrorMessage = "Invalid phone format"; } // Validate email (column D) string email = cells[3].StringValue; if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) { result.EmailErrorMessage = "Invalid email address"; } // Validate date (column E) if (!cells[4].IsDateTime) { result.DateErrorMessage = "Invalid date format"; } } using System.Text.RegularExpressions; using IronXL; // Validation implementation for (int i = 2; i <= 101; i++) { var result = new PersonValidationResult { Row = i }; results.Add(result); // Get cells for current person var cells = workSheet[$"A{i}:E{i}"].ToList(); // Validate phone (column B) string phone = cells[1].StringValue; if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$")) { result.PhoneNumberErrorMessage = "Invalid phone format"; } // Validate email (column D) string email = cells[3].StringValue; if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) { result.EmailErrorMessage = "Invalid email address"; } // Validate date (column E) if (!cells[4].IsDateTime) { result.DateErrorMessage = "Invalid date format"; } } $vbLabelText $csharpLabel 検証結果を新しいワークシートに保存します: // Create results worksheet var resultsSheet = workBook.CreateWorkSheet("ValidationResults"); // Add headers resultsSheet["A1"].Value = "Row"; resultsSheet["B1"].Value = "Valid"; resultsSheet["C1"].Value = "Phone Error"; resultsSheet["D1"].Value = "Email Error"; resultsSheet["E1"].Value = "Date Error"; // Style headers resultsSheet["A1:E1"].Style.Font.Bold = true; resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4"); resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF"; // Output validation results for (int i = 0; i < results.Count; i++) { var result = results[i]; int outputRow = i + 2; resultsSheet[$"A{outputRow}"].Value = result.Row; resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No"; resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? ""; resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? ""; resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? ""; // Highlight invalid rows if (!result.IsValid) { resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6"); } } // Auto-fit columns for (int col = 0; col < 5; col++) { resultsSheet.AutoSizeColumn(col); } // Save validated workbook workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx"); // Create results worksheet var resultsSheet = workBook.CreateWorkSheet("ValidationResults"); // Add headers resultsSheet["A1"].Value = "Row"; resultsSheet["B1"].Value = "Valid"; resultsSheet["C1"].Value = "Phone Error"; resultsSheet["D1"].Value = "Email Error"; resultsSheet["E1"].Value = "Date Error"; // Style headers resultsSheet["A1:E1"].Style.Font.Bold = true; resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4"); resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF"; // Output validation results for (int i = 0; i < results.Count; i++) { var result = results[i]; int outputRow = i + 2; resultsSheet[$"A{outputRow}"].Value = result.Row; resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No"; resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? ""; resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? ""; resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? ""; // Highlight invalid rows if (!result.IsValid) { resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6"); } } // Auto-fit columns for (int col = 0; col < 5; col++) { resultsSheet.AutoSizeColumn(col); } // Save validated workbook workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx"); $vbLabelText $csharpLabel Excelデータをデータベースにエクスポートするにはどうすればよいですか? Entity Frameworkを使用してIronXLでスプレッドシートデータを直接データベースにエクスポートします。 この例では、国のGDPデータをSQLiteにエクスポートする方法を示しています。 using System; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; using IronXL; // Define entity model public class Country { [Key] public Guid Id { get; set; } = Guid.NewGuid(); [Required] [MaxLength(100)] public string Name { get; set; } [Range(0, double.MaxValue)] public decimal GDP { get; set; } public DateTime ImportedDate { get; set; } = DateTime.UtcNow; } using System; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; using IronXL; // Define entity model public class Country { [Key] public Guid Id { get; set; } = Guid.NewGuid(); [Required] [MaxLength(100)] public string Name { get; set; } [Range(0, double.MaxValue)] public decimal GDP { get; set; } public DateTime ImportedDate { get; set; } = DateTime.UtcNow; } $vbLabelText $csharpLabel データベース操作のためにEntity Frameworkコンテキストを構成します: public class CountryContext : DbContext { public DbSet<Country> Countries { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Configure SQLite connection optionsBuilder.UseSqlite("Data Source=CountryGDP.db"); // Enable sensitive data logging in development #if DEBUG optionsBuilder.EnableSensitiveDataLogging(); #endif } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure decimal precision modelBuilder.Entity<Country>() .Property(c => c.GDP) .HasPrecision(18, 2); } } public class CountryContext : DbContext { public DbSet<Country> Countries { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Configure SQLite connection optionsBuilder.UseSqlite("Data Source=CountryGDP.db"); // Enable sensitive data logging in development #if DEBUG optionsBuilder.EnableSensitiveDataLogging(); #endif } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure decimal precision modelBuilder.Entity<Country>() .Property(c => c.GDP) .HasPrecision(18, 2); } } $vbLabelText $csharpLabel ご注意注: 異なるデータベースを使用するには、適切な NuGet パッケージ (SQL Server の場合はMicrosoft.EntityFrameworkCore.SqlServerなど) をインストールし、それに応じて接続構成を変更します。 Excelデータをデータベースにインポートします: using System.Threading.Tasks; using IronXL; using Microsoft.EntityFrameworkCore; public async Task ImportGDPDataAsync() { try { // Load Excel file var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx"); var workSheet = workBook.GetWorkSheet("GDPByCountry"); using (var context = new CountryContext()) { // Ensure database exists await context.Database.EnsureCreatedAsync(); // Clear existing data (optional) await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries"); // Import data with progress tracking int totalRows = 213; for (int row = 2; row <= totalRows; row++) { // Read country data var countryName = workSheet[$"A{row}"].StringValue; var gdpValue = workSheet[$"B{row}"].DecimalValue; // Skip empty rows if (string.IsNullOrWhiteSpace(countryName)) continue; // Create and add entity var country = new Country { Name = countryName.Trim(), GDP = gdpValue * 1_000_000 // Convert to actual value if in millions }; await context.Countries.AddAsync(country); // Save in batches for performance if (row % 50 == 0) { await context.SaveChangesAsync(); Console.WriteLine($"Imported {row - 1} of {totalRows} countries"); } } // Save remaining records await context.SaveChangesAsync(); Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries"); } } catch (Exception ex) { Console.WriteLine($"Import failed: {ex.Message}"); throw; } } using System.Threading.Tasks; using IronXL; using Microsoft.EntityFrameworkCore; public async Task ImportGDPDataAsync() { try { // Load Excel file var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx"); var workSheet = workBook.GetWorkSheet("GDPByCountry"); using (var context = new CountryContext()) { // Ensure database exists await context.Database.EnsureCreatedAsync(); // Clear existing data (optional) await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries"); // Import data with progress tracking int totalRows = 213; for (int row = 2; row <= totalRows; row++) { // Read country data var countryName = workSheet[$"A{row}"].StringValue; var gdpValue = workSheet[$"B{row}"].DecimalValue; // Skip empty rows if (string.IsNullOrWhiteSpace(countryName)) continue; // Create and add entity var country = new Country { Name = countryName.Trim(), GDP = gdpValue * 1_000_000 // Convert to actual value if in millions }; await context.Countries.AddAsync(country); // Save in batches for performance if (row % 50 == 0) { await context.SaveChangesAsync(); Console.WriteLine($"Imported {row - 1} of {totalRows} countries"); } } // Save remaining records await context.SaveChangesAsync(); Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries"); } } catch (Exception ex) { Console.WriteLine($"Import failed: {ex.Message}"); throw; } } $vbLabelText $csharpLabel APIデータをExcelスプレッドシートにインポートするにはどうすればよいですか? HTTPクライアントとIronXLを組み合わせてスプレッドシートをライブAPIデータで埋めます。 この例ではRestClient.Netを使用して国データを取得します。 using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using IronXL; // Define data model matching API response public class RestCountry { public string Name { get; set; } public long Population { get; set; } public string Region { get; set; } public string NumericCode { get; set; } public List<Language> Languages { get; set; } } public class Language { public string Name { get; set; } public string NativeName { get; set; } } // Fetch and process API data public async Task ImportCountryDataAsync() { using var httpClient = new HttpClient(); try { // Call REST API var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all"); var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response); // Create new workbook var workBook = WorkBook.Create(ExcelFileFormat.XLSX); var workSheet = workBook.CreateWorkSheet("Countries"); // Add headers with styling string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" }; for (int col = 0; col < headers.Length; col++) { var headerCell = workSheet[0, col]; headerCell.Value = headers[col]; headerCell.Style.Font.Bold = true; headerCell.Style.SetBackgroundColor("#366092"); headerCell.Style.Font.Color = "#FFFFFF"; } // Import country data await ProcessCountryData(countries, workSheet); // Save workbook workBook.SaveAs("CountriesFromAPI.xlsx"); } catch (Exception ex) { Console.WriteLine($"API import failed: {ex.Message}"); } } using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using IronXL; // Define data model matching API response public class RestCountry { public string Name { get; set; } public long Population { get; set; } public string Region { get; set; } public string NumericCode { get; set; } public List<Language> Languages { get; set; } } public class Language { public string Name { get; set; } public string NativeName { get; set; } } // Fetch and process API data public async Task ImportCountryDataAsync() { using var httpClient = new HttpClient(); try { // Call REST API var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all"); var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response); // Create new workbook var workBook = WorkBook.Create(ExcelFileFormat.XLSX); var workSheet = workBook.CreateWorkSheet("Countries"); // Add headers with styling string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" }; for (int col = 0; col < headers.Length; col++) { var headerCell = workSheet[0, col]; headerCell.Value = headers[col]; headerCell.Style.Font.Bold = true; headerCell.Style.SetBackgroundColor("#366092"); headerCell.Style.Font.Color = "#FFFFFF"; } // Import country data await ProcessCountryData(countries, workSheet); // Save workbook workBook.SaveAs("CountriesFromAPI.xlsx"); } catch (Exception ex) { Console.WriteLine($"API import failed: {ex.Message}"); } } $vbLabelText $csharpLabel APIはこの形式でJSONデータを返します: 階層的な国情報を示すREST Countries APIからのサンプルJSON応答。 APIデータを処理してExcelに書き込みます: private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet) { for (int i = 0; i < countries.Count; i++) { var country = countries[i]; int row = i + 1; // Start from row 1 (after headers) // Write basic country data workSheet[$"A{row}"].Value = country.Name; workSheet[$"B{row}"].Value = country.Population; workSheet[$"C{row}"].Value = country.Region; workSheet[$"D{row}"].Value = country.NumericCode; // Format population with thousands separator workSheet[$"B{row}"].FormatString = "#,##0"; // Add up to 3 languages for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++) { var language = country.Languages[langIndex]; string columnLetter = ((char)('E' + langIndex)).ToString(); workSheet[$"{columnLetter}{row}"].Value = language.Name; } // Add conditional formatting for regions if (country.Region == "Europe") { workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF"); } else if (country.Region == "Asia") { workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6"); } // Show progress every 50 countries if (i % 50 == 0) { Console.WriteLine($"Processed {i} of {countries.Count} countries"); } } // Auto-size all columns for (int col = 0; col < 7; col++) { workSheet.AutoSizeColumn(col); } } private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet) { for (int i = 0; i < countries.Count; i++) { var country = countries[i]; int row = i + 1; // Start from row 1 (after headers) // Write basic country data workSheet[$"A{row}"].Value = country.Name; workSheet[$"B{row}"].Value = country.Population; workSheet[$"C{row}"].Value = country.Region; workSheet[$"D{row}"].Value = country.NumericCode; // Format population with thousands separator workSheet[$"B{row}"].FormatString = "#,##0"; // Add up to 3 languages for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++) { var language = country.Languages[langIndex]; string columnLetter = ((char)('E' + langIndex)).ToString(); workSheet[$"{columnLetter}{row}"].Value = language.Name; } // Add conditional formatting for regions if (country.Region == "Europe") { workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF"); } else if (country.Region == "Asia") { workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6"); } // Show progress every 50 countries if (i % 50 == 0) { Console.WriteLine($"Processed {i} of {countries.Count} countries"); } } // Auto-size all columns for (int col = 0; col < 7; col++) { workSheet.AutoSizeColumn(col); } } $vbLabelText $csharpLabel オブジェクトリファレンスとリソース 詳細なクラスドキュメントと高度な機能に関する詳細は、包括的なIronXL APIリファレンスを探索してください。 Excel操作の追加のチュートリアル: プログラムでExcelファイルを作成する Excelのフォーマットとスタイルガイド Excelの数式の操作 Excelチャート作成チュートリアル まとめ IronXL.Excelは、さまざまなフォーマットでExcelファイルを読み取りおよび操作するための包括的な.NETライブラリです。 それはMicrosoft ExcelまたはInteropのインストールを必要とせずに独立して動作します。 クラウドベースのスプレッドシート操作には、IronXLのローカルファイル機能を補完するためにGoogle Sheets APIクライアントライブラリも探索することができます。 C#プロジェクトでExcel自動化を実装する準備はできましたか? IronXLをダウンロードまたは製品使用に関するライセンスオプションを探索してください。 よくある質問 Microsoft Officeを使用せずにC#でExcelファイルを読む方法は? Microsoft Officeを必要とせずにC#でExcelファイルを読むにはIronXLを使用できます。IronXLはWorkBook.Load()のようなメソッドを提供し、Excelファイルを開きデータを直感的な構文でアクセスおよび操作できます。 C#でどの形式のExcelファイルを読むことができますか? IronXLを使用すると、C#でXLSおよびXLSXファイル形式の両方を読むことができます。ライブラリはWorkBook.Load()メソッドを使用してファイル形式を自動的に検出し、対応する処理を行います。 C#でExcelデータをどのように検証しますか? IronXLを使用すると、C#でプログラム的にExcelデータを検証できます。セルを反復し、メール情報の正規表現やカスタム検証関数などのロジックを適用することができます。 CreateWorkSheet()を使用してレポートを生成できます。 C# を使用して Excel から SQL データベースにデータをエクスポートするにはどうすればよいですか? Excel から SQL データベースにデータをエクスポートするには、IronXL を使用して WorkBook.Load() と GetWorkSheet() メソッドで Excel データを読み取り、その後、セルを繰り返し処理して Entity Framework を使用し、データをデータベースに転送します。 ASP.NET Core アプリケーションに Excel 機能を統合できますか? はい、IronXLはASP.NET Coreアプリケーションとの統合をサポートしています。WorkBookおよびWorkSheetクラスをコントローラで使用してExcelファイルのアップロード、レポートの生成などを行うことができます。 C#を使用してExcelスプレッドシートに数式を追加することは可能ですか? IronXLを使用すると、プログラムでExcelスプレッドシートに数式を追加できます。Formulaプロパティを使用して数式を設定し(例:cell.Formula = "=SUM(A1:A10)")、workBook.EvaluateAll()を使用して結果を算出します。 REST APIからのデータでExcelファイルをどのように埋めることができますか? REST APIからのデータでExcelファイルを埋めるには、IronXLをHTTPクライアントと共に使用し、APIデータをフェッチした後、sheet["A1"].Valueのようなメソッドを使用してExcelに書き込みます。IronXLはExcelのフォーマットと構造を管理します。 プロダクション環境でExcelライブラリを使用する際のライセンスオプションは何ですか? IronXLは開発目的での無料トライアルを提供し、プロダクションライセンスは$749から開始します。これらのライセンスには専任の技術サポートが含まれ、追加のOfficeライセンスを必要とせずに様々な環境でのデプロイを可能にします。 Jacob Mellor 今すぐエンジニアリングチームとチャット 最高技術責任者(CTO) ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。彼の主要なIronPDFとIron Suite .NETライブラリは、世界中で3000万以上のNuGetインストールを達成し、彼の基礎となるコードは世界中で使用されている開発者ツールに力を与え続けています。25年の商業経験と41年のコーディングの専門知識を持つJacobは、次世代の技術リーダーを指導しながら、エンタープライズグレードのC#、Java、Python PDFテクノロジーにおけるイノベーションの推進に注力しています。 準備はできましたか? Nuget ダウンロード 1,913,565 | バージョン: 2026.3 リリース 無料トライアル NuGet 無料ダウンロード 総ダウンロード数: 1,913,565 ライセンスを見る まだスクロールしていますか? すぐに証拠が欲しいですか? PM > Install-Package IronXL.Excel サンプルを実行する あなたのデータがスプレッドシートになるのを見る。 NuGet 無料ダウンロード 総ダウンロード数: 1,913,565 ライセンスを見る