How to Create Excel Files in C# Without Interop
IronXLを使用してC#でExcelファイルを生成する方法を学びましょう。Microsoft Office依存なしでスプレッドシートの作成、読み取り、編集を可能にする強力な.NET Excelライブラリです。 この包括的なチュートリアルは、ステップバイステップのコード例を用いてプログラムでExcelワークブックを構築する方法を案内します。
クイックスタート: シンプルな1行でのExcelワークブック作成
IronXLを使用してすぐに新しいExcelファイルを立ち上げましょう。フォーマットを選択し、シートを追加し、任意のセル値を設定して保存するだけです。 直感的なAPIコールとInteropの悩みゼロでXLSXファイルを生成する最も速い方法です。
Get started making PDFs with NuGet now:
Install IronXL with NuGet Package Manager
Copy and run this code snippet.
WorkBook book = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");Deploy to test on your live environment
class="tutorial-segment-title">概要
最小限のワークフロー(5ステップ)
- C#ライブラリをダウンロードしてExcelおよびCSVファイルを作成する
- ASP.NETプロジェクトのWebアプリケーションを作成する
- IronXLでExcelワークブックを作成する
- Excelワークシートにセルの値を設定する
- フォーマットを適用し、背景色を設定する
- セルに数式を使用する
- ワークシートと印刷のプロパティを設定する
- Excelワークブックを保存する
IronXLとは、なぜExcelファイル作成に使用するのか?
IronXLは直感的なC# & VB Excel APIで、.NETでExcelスプレッドシートファイルを読み取り、編集、作成することを優れたパフォーマンスで可能にします。 従来のアプローチとは異なり、Microsoft OfficeのインストールやExcel Interopの使用が不要で、デプロイがよりシンプルで信頼性があります。
IronXLは、.NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、モバイル、Linux、macOS、およびAzure環境を完全にサポートしています。
IronXLの機能
- .NET開発チームからの直接のサポート
- Microsoft Visual Studioでの迅速なインストール
- 開発用に無料。 ライセンスは$799から
Excelファイルをすばやく作成して保存する方法は?
Install IronXL via NuGet or DLLを直接ダウンロードしてください。
using IronXL;
// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");
// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";
// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;
// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");
// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;
// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";
// Calculate all formulas to show results
workSheet.EvaluateAll();
// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
Console.WriteLine("Formula calculation successful!");
}
// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
using IronXL;
// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");
// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";
// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;
// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");
// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;
// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";
// Calculate all formulas to show results
workSheet.EvaluateAll();
// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
Console.WriteLine("Formula calculation successful!");
}
// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
Imports IronXL
' Create a new Excel workbook with XLSX format
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Add a worksheet to the workbook
Private workSheet = workBook.CreateWorkSheet("example_sheet")
' Set individual cell values using intuitive syntax
Private workSheet("A1").Value = "Example"
' Set multiple cells at once using range syntax
Private workSheet("A2:A4").Value = 5
' Apply cell styling - set background color using hex code
workSheet("A5").Style.SetBackgroundColor("#f0f0f0")
' Make text bold for better visibility
workSheet("A5:A6").Style.Font.Bold = True
' Add Excel formula to calculate sum
workSheet("A6").Formula = "=SUM(A2:A4)"
' Calculate all formulas to show results
workSheet.EvaluateAll()
' Verify formula calculation worked correctly
If workSheet("A6").IntValue = 15 Then ' Sum of three cells with value 5
Console.WriteLine("Formula calculation successful!")
End If
' Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx")
このコードは、ワークブック作成、ワークシート追加、セルの値とスタイル設定、数式の使用、ファイルの保存といったIronXLの主要機能を示しています。 The WorkBook class serves as your entry point for all Excel operations, while the WorkSheet class provides methods to manipulate individual sheets.
class="tutorial-segment-title">ステップ 1
1. IronXL C#ライブラリをインストールする方法は?
NuGetを使用して(Install-Package IronXL)またはDLLを直接ダウンロードしてIronXLライブラリをインストールします。
今日あなたのプロジェクトでIronXLを無料トライアルで使用開始。
NuGetを使用してIronXLをインストールする方法は?
IronXL NuGetパッケージをインストールするには3つの方法があります:
- Visual Studioパッケージ マネージャー
- 開発者コマンドプロンプト
- NuGet.orgから直接ダウンロード
Visual Studioでのインストール
Visual Studioは簡単なパッケージインストール用のNuGetパッケージマネージャを提供しています。 プロジェクトメニューからまたはソリューションエクスプローラーでプロジェクトを右クリックしてアクセスします。
NuGetパッケージの管理をクリックした後、IronXL.Excelパッケージを参照してインストールします。
開発者コマンドプロンプトでのインストール
このコマンドを使用してパッケージ マネージャ コンソールを使用してください:
Install-Package IronXL.Excel
直接ダウンロードインストール
- 移動先: https://www.nuget.org/packages/IronXL.Excel/
- パッケージのダウンロードをクリック
- ダウンロードしたパッケージをダブルクリック
- Visual Studioプロジェクトをリロード
DLLをダウンロードしてIronXLをインストールする方法は?
IronXLを直接ダウンロード: https://ironsoftware.com/csharp/excel/
プロジェクトでライブラリを参照:
- ソリューション エクスプローラーでソリューションを右クリック
- リファレンスを選択
- IronXL.dllライブラリを参照
- OKをクリック
進めましょう!
これでIronXLの強力なExcel操作機能を探索する準備が整いました!
class="tutorial-segment-title">チュートリアルとガイド
2. Excel生成用ASP.NETプロジェクトを作成するにはどうすればよいですか?
以下の手順に従って、ASP.NETサイトを作成します:
- Visual Studioを開く
- ファイル > 新規プロジェクトをクリック
- プロジェクトタイプ一覧でVisual C#の下のWebを選択
-
ASP.NET Webアプリケーションを選択
Figure 1 – 新しいASP.NETプロジェクトを作成
- OKをクリック
-
Web Formsテンプレートを選択
Figure 2 – *Web Formsテンプレートの選択*
- OKをクリック
プロジェクトが準備できたら、IronXLをインストールしてプログラムでExcelファイルを作成し始めましょう。
3. C#でExcelワークブックを作成するにはどうすればよいですか?
IronXLを使った新しいExcelワークブックの作成は1行のコードのみ必要です:
using IronXL;
// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
using IronXL;
// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
Imports IronXL
' Create workbook with XLSX format (recommended for modern Excel)
Private workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Alternative: Create legacy XLS format for older Excel versions
Private legacyWorkbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
WorkBook.CreateメソッドはXLS(Excel 97-2003)およびXLSX(Excel 2007+)フォーマットをサポートしています。 より良いパフォーマンスと小さなファイルサイズを得るためにXLSXを推奨します。
3.1. ワークブックにワークシートを追加するには?
ワークシートを追加するのは簡単です:
// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");
// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");
// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");
// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");
// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
' Create a worksheet with custom name for budget tracking
Dim budgetSheet As WorkSheet = workbook.CreateWorkSheet("2020 Budget")
' Add multiple worksheets for different purposes
Dim salesSheet As WorkSheet = workbook.CreateWorkSheet("Sales Data")
Dim inventorySheet As WorkSheet = workbook.CreateWorkSheet("Inventory")
' Access existing worksheet by name
Dim existingSheet As WorkSheet = workbook.GetWorkSheet("2020 Budget")
ワークブックは1つ以上のワークシートを含みます。 各ワークシートは行と列で構成され、それらの交差点にはセルがあります。 CreateWorkSheetメソッドを使用してワークブックに新しいシートを追加します。
4. Excelでセルの値を設定するにはどうすればよいですか?
4.1. セルの値を手動で設定するには?
個別のセルの値の設定は直感的なExcel風の構文を使用します:
// Set month names in first row for annual budget spreadsheet
workSheet["A1"].Value = "January";
workSheet["B1"].Value = "February";
workSheet["C1"].Value = "March";
workSheet["D1"].Value = "April";
workSheet["E1"].Value = "May";
workSheet["F1"].Value = "June";
workSheet["G1"].Value = "July";
workSheet["H1"].Value = "August";
workSheet["I1"].Value = "September";
workSheet["J1"].Value = "October";
workSheet["K1"].Value = "November";
workSheet["L1"].Value = "December";
// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m; // Decimal for currency
workSheet["A3"].Value = DateTime.Now; // Date values
workSheet["A4"].Value = true; // Boolean values
// Set month names in first row for annual budget spreadsheet
workSheet["A1"].Value = "January";
workSheet["B1"].Value = "February";
workSheet["C1"].Value = "March";
workSheet["D1"].Value = "April";
workSheet["E1"].Value = "May";
workSheet["F1"].Value = "June";
workSheet["G1"].Value = "July";
workSheet["H1"].Value = "August";
workSheet["I1"].Value = "September";
workSheet["J1"].Value = "October";
workSheet["K1"].Value = "November";
workSheet["L1"].Value = "December";
// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m; // Decimal for currency
workSheet["A3"].Value = DateTime.Now; // Date values
workSheet["A4"].Value = true; // Boolean values
' Set month names in first row for annual budget spreadsheet
workSheet("A1").Value = "January"
workSheet("B1").Value = "February"
workSheet("C1").Value = "March"
workSheet("D1").Value = "April"
workSheet("E1").Value = "May"
workSheet("F1").Value = "June"
workSheet("G1").Value = "July"
workSheet("H1").Value = "August"
workSheet("I1").Value = "September"
workSheet("J1").Value = "October"
workSheet("K1").Value = "November"
workSheet("L1").Value = "December"
' Set different data types - IronXL handles conversion automatically
workSheet("A2").Value = 1500.50D ' Decimal for currency
workSheet("A3").Value = DateTime.Now ' Date values
workSheet("A4").Value = True ' Boolean values
Cell.Valueプロパティは文字列、数字、日付、ブール値などのさまざまなデータタイプを受け入れます。 IronXLはデータタイプに基づいてセルを自動的にフォーマットします。
4.2. セルの値を動的に設定するには?
動的な値設定はデータ駆動型アプリケーションに最適です:
// Initialize random number generator for sample data
Random r = new Random();
// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
// Set different budget categories with increasing ranges
workSheet[$"A{i}"].Value = r.Next(1, 1000); // Office Supplies
workSheet[$"B{i}"].Value = r.Next(1000, 2000); // Utilities
workSheet[$"C{i}"].Value = r.Next(2000, 3000); // Rent
workSheet[$"D{i}"].Value = r.Next(3000, 4000); // Salaries
workSheet[$"E{i}"].Value = r.Next(4000, 5000); // Marketing
workSheet[$"F{i}"].Value = r.Next(5000, 6000); // IT Services
workSheet[$"G{i}"].Value = r.Next(6000, 7000); // Travel
workSheet[$"H{i}"].Value = r.Next(7000, 8000); // Training
workSheet[$"I{i}"].Value = r.Next(8000, 9000); // Insurance
workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}
// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
// Initialize random number generator for sample data
Random r = new Random();
// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
// Set different budget categories with increasing ranges
workSheet[$"A{i}"].Value = r.Next(1, 1000); // Office Supplies
workSheet[$"B{i}"].Value = r.Next(1000, 2000); // Utilities
workSheet[$"C{i}"].Value = r.Next(2000, 3000); // Rent
workSheet[$"D{i}"].Value = r.Next(3000, 4000); // Salaries
workSheet[$"E{i}"].Value = r.Next(4000, 5000); // Marketing
workSheet[$"F{i}"].Value = r.Next(5000, 6000); // IT Services
workSheet[$"G{i}"].Value = r.Next(6000, 7000); // Travel
workSheet[$"H{i}"].Value = r.Next(7000, 8000); // Training
workSheet[$"I{i}"].Value = r.Next(8000, 9000); // Insurance
workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}
// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
' Initialize random number generator for sample data
Dim r As New Random()
' Populate cells with random budget data for each month
For i As Integer = 2 To 11
' Set different budget categories with increasing ranges
workSheet($"A{i}").Value = r.Next(1, 1000) ' Office Supplies
workSheet($"B{i}").Value = r.Next(1000, 2000) ' Utilities
workSheet($"C{i}").Value = r.Next(2000, 3000) ' Rent
workSheet($"D{i}").Value = r.Next(3000, 4000) ' Salaries
workSheet($"E{i}").Value = r.Next(4000, 5000) ' Marketing
workSheet($"F{i}").Value = r.Next(5000, 6000) ' IT Services
workSheet($"G{i}").Value = r.Next(6000, 7000) ' Travel
workSheet($"H{i}").Value = r.Next(7000, 8000) ' Training
workSheet($"I{i}").Value = r.Next(8000, 9000) ' Insurance
workSheet($"J{i}").Value = r.Next(9000, 10000) ' Equipment
workSheet($"K{i}").Value = r.Next(10000, 11000) ' Research
workSheet($"L{i}").Value = r.Next(11000, 12000) ' Misc
Next i
' Alternative: Set range of cells with same value
workSheet("A13:L13").Value = 0 ' Initialize totals row
文字列補完($"A{i}")はセルを動的に簡単に参照することができます。 Rangeインデクサは個々のセルと範囲の両方をサポートします。
4.3. データベースからExcelにポピュレートするにはどうすればよいですか?
データベースからExcelにデータをロードすることは一般的な要件です:
using System.Data;
using System.Data.SqlClient;
using IronXL;
// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";
// Create DataSet to hold query results
DataSet salesData = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
// Fill DataSet with sales information
adapter.Fill(salesData);
}
// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";
// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";
// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Count; row++)
{
int excelRow = row + 2; // Start from row 2 (after headers)
workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);
// Format currency columns
workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}
// Add summary row with formulas
int summaryRow = salesTable.Rows.Count + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
using System.Data;
using System.Data.SqlClient;
using IronXL;
// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";
// Create DataSet to hold query results
DataSet salesData = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
// Fill DataSet with sales information
adapter.Fill(salesData);
}
// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";
// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";
// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Count; row++)
{
int excelRow = row + 2; // Start from row 2 (after headers)
workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);
// Format currency columns
workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}
// Add summary row with formulas
int summaryRow = salesTable.Rows.Count + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
Imports System.Data
Imports System.Data.SqlClient
Imports IronXL
' Database connection setup for retrieving sales data
Private connectionString As String = "Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true"
Private query As String = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales"
' Create DataSet to hold query results
Private salesData As New DataSet()
Using connection As New SqlConnection(connectionString)
Using adapter As New SqlDataAdapter(query, connection)
' Fill DataSet with sales information
adapter.Fill(salesData)
End Using
End Using
' Write headers for database columns
workSheet("A1").Value = "Product Name"
workSheet("B1").Value = "Quantity"
workSheet("C1").Value = "Unit Price"
workSheet("D1").Value = "Total Sales"
' Apply header formatting
workSheet("A1:D1").Style.Font.Bold = True
workSheet("A1:D1").Style.SetBackgroundColor("#4472C4")
workSheet("A1:D1").Style.Font.FontColor = "#FFFFFF"
' Populate Excel with database records
Dim salesTable As DataTable = salesData.Tables(0)
For row As Integer = 0 To salesTable.Rows.Count - 1
Dim excelRow As Integer = row + 2 ' Start from row 2 (after headers)
workSheet($"A{excelRow}").Value = salesTable.Rows(row)("ProductName").ToString()
workSheet($"B{excelRow}").Value = Convert.ToInt32(salesTable.Rows(row)("Quantity"))
workSheet($"C{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("UnitPrice"))
workSheet($"D{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("TotalSales"))
' Format currency columns
workSheet($"C{excelRow}").FormatString = "$#,##0.00"
workSheet($"D{excelRow}").FormatString = "$#,##0.00"
Next row
' Add summary row with formulas
Dim summaryRow As Integer = salesTable.Rows.Count + 2
workSheet($"A{summaryRow}").Value = "TOTAL"
workSheet($"B{summaryRow}").Formula = $"=SUM(B2:B{summaryRow-1})"
workSheet($"D{summaryRow}").Formula = $"=SUM(D2:D{summaryRow-1})"
この例は、データベースからのExcelデータの読み取り、フォーマットの適用、および計算のための数式の使用を示しています。 FormatStringプロパティは、Excelと同様にカスタムの数値フォーマットを可能にします。
5. Excelのセルに書式を適用するにはどうすればよいですか?
5.1. Excelで背景色を設定するには?
セルのスタイリングは可読性と視覚的魅力を強化します:
// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");
// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February
// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.FontColor = "#FFFFFF"; // White text
// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
if (row % 2 == 0)
{
workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}
// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");
// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February
// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.FontColor = "#FFFFFF"; // White text
// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
if (row % 2 == 0)
{
workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}
' Set header row background to light gray using hex color
workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")
' Apply different colors for data categorization
workSheet("A2:A11").Style.SetBackgroundColor("#E7F3FF") ' Light blue for January
workSheet("B2:B11").Style.SetBackgroundColor("#FFF2CC") ' Light yellow for February
' Highlight important cells with bold colors
workSheet("L12").Style.SetBackgroundColor("#FF0000") ' Red for totals
workSheet("L12").Style.Font.FontColor = "#FFFFFF" ' White text
' Create alternating row colors for better readability
For row As Integer = 2 To 11
If row Mod 2 = 0 Then
workSheet($"A{row}:L{row}").Style.SetBackgroundColor("#F2F2F2")
End If
Next row
Style.SetBackgroundColorメソッドは16進数の色コードを受け入れます。 背景色とフォントカラーを組み合わせてプロフェッショナルな外観のスプレッドシートを作成します。
5.2. Excelで枠線を作成するには?
枠線はデータ領域を定義し、構造を改善します:
using IronXL;
using IronXL.Styles;
// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;
// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;
// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;
// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
using IronXL;
using IronXL.Styles;
// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;
// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;
// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;
// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
Imports IronXL
Imports IronXL.Styles
' Create header border - thick bottom line to separate from data
workSheet("A1:L1").Style.TopBorder.SetColor("#000000")
workSheet("A1:L1").Style.TopBorder.Type = BorderType.Thick
workSheet("A1:L1").Style.BottomBorder.SetColor("#000000")
workSheet("A1:L1").Style.BottomBorder.Type = BorderType.Thick
' Add right border to last column
workSheet("L2:L11").Style.RightBorder.SetColor("#000000")
workSheet("L2:L11").Style.RightBorder.Type = BorderType.Medium
' Create bottom border for data area
workSheet("A11:L11").Style.BottomBorder.SetColor("#000000")
workSheet("A11:L11").Style.BottomBorder.Type = BorderType.Medium
' Apply complete border around summary section
Dim summaryRange = workSheet("A12:L12")
summaryRange.Style.TopBorder.Type = BorderType.Double
summaryRange.Style.BottomBorder.Type = BorderType.Double
summaryRange.Style.LeftBorder.Type = BorderType.Thin
summaryRange.Style.RightBorder.Type = BorderType.Thin
summaryRange.Style.SetBorderColor("#0070C0") ' Blue borders
IronXLは様々な枠線のタイプ(薄い、中くらい、太い、ダブル、点線、破線)をサポートしています。 各枠線の側面は独立してスタイリングできます。
6. C#でExcelの数式を使用するにはどうすればよいですか?
IronXLは自動計算を備えた強力な数式のサポートを提供します:
// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();
// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;
// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";
// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";
// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";
// Ensure all formulas calculate
workSheet.EvaluateAll();
// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();
// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;
// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";
// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";
// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";
// Ensure all formulas calculate
workSheet.EvaluateAll();
' Use built-in aggregation functions for ranges
Dim sum As Decimal = workSheet("A2:A11").Sum()
Dim avg As Decimal = workSheet("B2:B11").Avg()
Dim max As Decimal = workSheet("C2:C11").Max()
Dim min As Decimal = workSheet("D2:D11").Min()
' Assign calculated values to cells
workSheet("A12").Value = sum
workSheet("B12").Value = avg
workSheet("C12").Value = max
workSheet("D12").Value = min
' Or use Excel formulas directly
workSheet("A12").Formula = "=SUM(A2:A11)"
workSheet("B12").Formula = "=AVERAGE(B2:B11)"
workSheet("C12").Formula = "=MAX(C2:C11)"
workSheet("D12").Formula = "=MIN(D2:D11)"
' Complex formulas with multiple functions
workSheet("E12").Formula = "=IF(SUM(E2:E11)>50000,""Over Budget"",""On Track"")"
workSheet("F12").Formula = "=SUMIF(F2:F11,"">5000"")"
' Percentage calculations
workSheet("G12").Formula = "=G11/SUM(G2:G11)*100"
workSheet("G12").FormatString = "0.00%"
' Ensure all formulas calculate
workSheet.EvaluateAll()
RangeクラスはSum()、Avg()、Max()、Min()といったクイック計算のメソッドを提供します。 より複雑なシナリオの場合は、Formulaプロパティを使用してExcelの数式を直接設定します。
7. ワークシートと印刷プロパティを設定するにはどうすればよいですか?
個別のワークシートを保護し、行と列を固定し、印刷フォーマットオプションを設定するためにIronXLを使用します。
7.1. ワークシートのプロパティを構成するにはどうすればよいですか?
ワークシートを保護し、表示オプションを制御します:
// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");
// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column
// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden
// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;
// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");
// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column
// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden
// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;
// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
' Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123")
' Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1) ' Freeze first row
' workSheet.CreateFreezePane(1, 1); // Freeze first row and column
' Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible ' or Hidden, VeryHidden
' Configure gridlines and headers
workSheet.ShowGridLines = True
workSheet.ShowRowColHeaders = True
' Set zoom level for better viewing
workSheet.Zoom = 85 ' 85% zoom
ワークシートの保護は誤った変更を防止し、ウィンドウ枠の固定はスクロール中に重要な行や列を表示し続けます。
7.2. ページと印刷設定を構成するにはどうすればよいですか?
IronXLのを通じてプロフェッショナルな印刷オプションを設定します:
using IronXL.Printing;
// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");
// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;
// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;
// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;
// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;
// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;
// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
using IronXL.Printing;
// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");
// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;
// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;
// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;
// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;
// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;
// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
Imports IronXL.Printing
' Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12")
' Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape
' Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4
' Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5
workSheet.PrintSetup.RightMargin = 0.5
workSheet.PrintSetup.TopMargin = 0.75
workSheet.PrintSetup.BottomMargin = 0.75
' Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3
workSheet.PrintSetup.FooterMargin = 0.3
' Scale to fit on one page
workSheet.PrintSetup.FitToPage = True
workSheet.PrintSetup.FitToHeight = 1
workSheet.PrintSetup.FitToWidth = 1
' Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report"
workSheet.Footer.Left = DateTime.Now.ToShortDateString()
workSheet.Footer.Right = "Page &P of &N" ' Page numbering
PrintSetupクラスはExcelの印刷設定に一致する包括的な印刷構成オプションを提供します。
8. Excelワークブックを保存するにはどうすればよいですか?
ワークブックを様々なフォーマットで保存します:
// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");
// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");
// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");
// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");
// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
workBook.SaveAs(stream);
byte[] excelData = stream.ToArray();
// Send to client or save to cloud
}
// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");
// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");
// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");
// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");
// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
workBook.SaveAs(stream);
byte[] excelData = stream.ToArray();
// Send to client or save to cloud
}
// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
' Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx")
' Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls")
' Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv")
' Save as JSON for web applications
workBook.SaveAsJson("Budget.json")
' Save to stream for web downloads or cloud storage
Using stream = New MemoryStream()
workBook.SaveAs(stream)
Dim excelData() As Byte = stream.ToArray()
' Send to client or save to cloud
End Using
' Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8)
IronXLはXLSX、XLS、CSV、TSV、JSONを含む複数のエクスポートフォーマットをサポートします。 SaveAsメソッドはファイル拡張子から自動的にフォーマットを決定します。
まとめ
このチュートリアルでは、IronXLを使用してMicrosoft Office依存を持たないC#でExcelファイルを作成する方法を示しました。 ワークブック作成、セル操作、フォーマット設定、数式使用、および様々な保存オプションを含む重要なExcel操作を学びました。 IronXLの直感的なAPIは、.NET開発者にとってExcelの自動化を簡単にします。
For more advanced features, explore merging cells, and creating charts. IronXLを製品で使用する準備ができましたか? Start your free trial or ライセンスオプションを表示します。
class="tutorial-segment-title">チュートリアルクイックアクセス
このチュートリアルをC#ソースコードとしてダウンロード
Excelファイルを作成するための完全なC#ソースコードがVisual Studioプロジェクトファイルとして提供されています。
ダウンロードGitHub上でこのチュートリアルを探る
このプロジェクトのソースコードはC#およびVB.NETでGitHub上で利用可能です。
このコードを使えば、数分でExcelファイル作成を始めることができます。プロジェクトはMicrosoft Visual Studioプロジェクトとして保存されていますが、どの.NET IDEでも互換性があります。
GitHub上でC#でExcelファイルを作成IronXL APIリファレンスを読む
IronXLのAPIリファレンスを探索し、.NETでの包括的なExcel操作のためのすべての機能、名前空間、クラス、メソッド、プロパティを詳述します。
APIリファレンスを表示よくある質問
Interopを使用せずにC#でExcelファイルを作成するにはどうすればよいですか?
IronXLを使用してInteropなしでExcelファイルを作成できます。これはシンプルなAPIを提供します:WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX)。この方法は、Microsoft Officeのインストールを必要とせず、任意の.NETプラットフォームで動作します。
C#でのExcelファイル作成はどのプラットフォームをサポートしますか?
IronXLはExcelファイルの作成を.NET 10、.NET 9、.NET 8、.NET Core、.NET Framework 4.6.2+でサポートし、Windows、macOS、Linux、Docker、Azure、AWS環境で実行できます。
Excel生成用のC#ライブラリをどのようにインストールしますか?
Visual StudioのNuGetパッケージマネージャーからIronXLをインストールし、コマンドPM> Install-Package IronXL.Excelを使用するか、nuget.orgから直接ダウンロードしてください。
プログラムで新しいExcelワークブックをどのように作成しますか?
IronXLを使用してワークブックを作成し、WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX)を使用してからworkbook.CreateWorkSheet("SheetName")でワークシートを追加します。
C#を使用してExcelワークシートのセル値をどのように設定しますか?
IronXLを使用して直感的な構文でセル値を設定します:worksheet["A1"].Value = "Hello World"または範囲を設定します:worksheet["A1:A10"].Value = 100。
プログラムでExcelのセルに書式を適用できますか?
はい、IronXLは背景色(cell.Style.SetBackgroundColor("#FF0000"))、罫線、フォント、数字の書式を含む包括的な書式設定をサポートします。
C#でExcelの数式をどのように使用しますか?
IronXLのFormulaプロパティを使用して数式を適用します:worksheet["A1"].Formula = "=SUM(B1:B10)"、またはrange.Sum()、range.Avg()のような組み込みメソッドを使用します。
パスワードでExcelワークシートをどのように保護しますか?
無許可の変更を防ぐために、worksheet.ProtectSheet("YourPassword")を使用してIronXLのワークシートを保護します。
Excelファイルの印刷設定を構成するにはどうすればよいですか?
IronXLのPrintSetupを使用して印刷プロパティを設定します:worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape と worksheet.SetPrintArea("A1:Z100").
Excelブックを異なる形式で保存するにはどうすればよいですか?
IronXLのSaveAsメソッドを使用してブックを保存します:workbook.SaveAs("file.xlsx")はXLSX形式のため、または他の形式のためにSaveAsCsv()、SaveAsJson()を使用します。
データベースからデータを取得してExcelシートにどのように入力しますか?
IronXLを使用してデータベースからデータを取得し、worksheet["A1"].Value = dataFromDatabaseのようなメソッドを使用してセルに設定します。
C#を使用してExcelシートでウインドウ枠の固定をどのように実装しますか?
IronXLを使用してワークシートでウインドウ枠の固定を行います:worksheet.FreezePanes(1, 1)で最上行と最左列をロックし、ナビゲーションを容易にします。








