跳至頁尾內容
與其他組件的比較

IronXL 和 Epplus 的比較

IronXL和EPPlus都是.NET Excel程式庫,可以讀取和建立.xlsx檔案,而無需安裝Microsoft Office或Interop。本比較涵蓋了它們的API、支援的格式和授權條款,並提供.NET應用程式中最常用操作的程式碼範例。

什麼是EPPlus軟體?

EPPlus是一個基於NuGet的.NET Framework/.NET Core程式庫,用於處理Office Open XML試算表。 版本5支持.NET Framework 3.5和.NET Core 2.0。EPPlus不依賴於任何其他程式庫,如Microsoft Excel。

EPPlus的API允許您操作Office Excel文件。 EPPlus是一個.NET程式庫,讀取和寫入Office OpenXML格式的Excel檔案。 此程式庫作為NuGet套件提供。

此程式庫是為程式設計師考慮而建立的。 目標一直是讓熟悉Excel或其他試算表程式庫的開發人員能夠快速學習API。 或者,有人這樣說,"用IntelliSense走向勝利!"

EPPlus安裝

要從Visual Studio安裝EPPlus,請轉到檢視 > 其他視窗 > 套件管理器控制台,然後鍵入以下命令:

Install-Package EPPlus

如果您更願意使用.NET CLI,請從已提升權限的命令提示符或PowerShell提示符運行以下命令:

dotnet add package EPPlus

EPPlus是一個.NET套件,可以新增到您的項目中。

什麼是IronXL?

IronXL是一個C#和VB Excel API,允許您在.NET中讀取、編輯和建立Excel試算表檔案,無需安裝Microsoft Office或依賴Excel Interop。該程式庫本身處理XLS、XLSX、CSV和其他試算表格式。

.NET Core、.NET Framework、Xamarin、移動裝置、Linux、macOS和Azure都支持IronXL。

有多種不同的方式可以將資料讀寫至試算表。

使用NuGet套件新增IronXL

我們可以通過三種方式之一將IronXL套件新增到您的帳戶中,因此您可以選擇最適合您的方式。

  • 使用套件管理器控制台安裝IronXL

在項目中打開套件管理器控制台,使用以下命令:

要存取套件管理器控制台,請轉到工具 => NuGet套件管理器 => 套件管理器控制台。

Epplus Read Create Excel Alternative 1 related to 使用NuGet套件新增IronXL

這將帶您進入套件管理器控制台。 然後在套件管理器終端中輸入以下命令:

Install-Package IronXL.Excel
Epplus Read Create Excel Alternative 2 related to 使用NuGet套件新增IronXL
  • 使用NuGet套件管理器安裝IronXL

這是獲得NuGet套件管理器安裝的另一種方法。 如果您之前已經使用先前的方法完成安裝,則無需使用此方法。

要存取NuGet套件管理器,請轉到工具 > NuGet套件管理器 => 從下拉選單中選擇對解決方案管理NuGet套件。

這將啟動NuGet-解決方案; 選擇"瀏覽"並查找IronXL。

在搜索欄中輸入Excel:

Epplus Read Create Excel Alternative 3 related to 使用NuGet套件新增IronXL

當您點擊"安裝"按鈕時,IronXL將為您安裝。 安裝IronXL後,您可以轉到您的表單並開始開發它。

在深入探討程式碼範例之前,這裡有一個對照圖表,展示了本文中討論的關鍵領域中EPPlus和IronXL的對比:

功能 EPPlus IronXL
讀取XLSX檔案
建立XLSX檔案
支持XLS格式
導出至CSV、JSON、XML 僅限CSV CSV、JSON、XML
資料庫導出(Entity Framework) 不包含
資料驗證助手 不包含
多工作簿操作 單工作表專注 多工作表和多工作簿
授權 商業或Polyform非商業 商業(永久)

要在自己的項目中測試IronXL與EPPlus的Excel操作,可免費試用30天

使用IronXL建立Excel檔案

使用IronXL建立新的Excel工作簿只需一行程式碼:

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

IronXL可以建立XLS(舊版Excel檔案格式)和XLSX(現行和更新的Excel檔案格式)格式的檔案,利用完整的Excel功能

  • 設置預設工作表

設置預設工作表甚至更簡單:

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

在上述程式碼片段中,工作表由sheet表示,您可以用它來設置單元格值和樣式,並幾乎執行Excel能夠做到的所有操作。 您還可以將您的Excel文件設定為只讀檔案並執行刪除操作。 您還可以像Excel一樣連結您的工作表。

如果您不確定,我來澄清一下工作簿和工作表之間的區別。

工作表包含在工作簿中。 這意味著您可以在工作簿中放置無數的工作表。 我會在後續文章中解釋如何做到這一點。 工作表由行和列組成。 行和列的交集稱為單元格,這是您在Excel中將與之互動的物件。

使用EPPlus Software AB建立Excel檔案

EPPlus可以用來建立Excel檔案並執行建立旋轉表、旋轉區域、甚至格式化條件和更改字體等操作。 事不宜遲,以下是將普通DataTable轉換為XLSX Excel文件並發送給使用者下載的完整源程式碼:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

如您所見,這是一個可以在任何ASP.NET MVC控制器上使用的ActionResult方法; 如果您不使用ASP.NET MVC,只需複製方法內容並將其粘貼到您需要的地方(例如,經典ASP.NET、控制台應用程式、Windows Forms等)。

該程式碼是自明式的,並提供足夠的註釋以幫助您理解各種處理過程。 但首先,快速回顧一下我們在這裡所做的事情:

  • 使用自定義資料提供者方法,我們獲得DataTable物件。
  • 我們建立一個ExcelPackage物件,它是EPPlus的XLSX文件的主要容器。
  • 我們將ExcelPackage,這將是資料將被輸入的工作表。
  • 為了建立我們的標題行,我們遍歷DataTable列,將它們新增到我們工作表的第一行。
  • 我們遍歷DataTable行對應於工作表行。
  • ExcelPackage二進制資料,然後將其轉換為字節陣列。
  • 我們建立HTML回應,並以Content-Disposition附件的形式將XLSX文件發送給使用者,使瀏覽器自動下載文件。

IronXL建立工作簿的方法需要一行程式碼,而EPPlus則需要多步設置,包括ExcelWorksheet和手動單元格迭代。 對於重視快速原型設計和簡單除錯的團隊來說,這種樣板程式碼上的差異在整個專案生命週期中可能會慢慢累積。

EPPlusSoftware AB如何寫入Excel檔案

EPPlus支持使用Excel檔案。 這是一個.NET程式庫,能夠讀取和寫入Excel檔案。

  • 讀取Excel檔案

為此,您首先需要安裝EPPlus套件:轉到"工具"-> "NuGet套件管理器"-> "管理此解決方案的NuGet" -> "安裝EPPlus" -> "安裝EPPlus" -> "安裝EPPlus" -> "安裝EPPlus" -> 安裝EP。 在"瀏覽"標籤中搜索"EPPlus",然後安裝NuGet套件。

Epplus Read Create Excel Alternative 4 related to EPPlusSoftware AB如何寫入Excel檔案

安裝套件後,可以在控制台應用程式"Program.cs"中使用以下程式碼。

using OfficeOpenXml;
using System;
using System.IO;

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

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

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

以下是包含範例excel檔案(.xlsx)的控制台應用程式輸出。 這是一個用EPPlus在C#中讀取的xlsx檔案。

Epplus Read Create Excel Alternative 5 related to EPPlusSoftware AB如何寫入Excel檔案

使用"cells"屬性(ExcelRange)可以存取從多個來源載入資料的以下方法:

  • 閱讀CSV文字文件並使用LoadFromTextAsync將資料載入到工作表的範圍。 IronXL還提供自己的CSV導出和導入操作
  • LoadFromDataReaderAsyncLoadFromDataReader —— 將DataReader中的資料字段載入到範圍中。
  • LoadFromDataTable —— 將資料從DataTable載入到範圍。 它可以從各種來源導入資料,包括XML(提供了一個範例)和資料庫。
  • LoadFromCollection —— 從IEnumerable反映性地載入資料到範圍中。
  • 具有屬性的LoadFromCollection — 從IEnumerable反映性地載入資料到範圍或表中。 通過屬性指定風格、數字格式、公式和其他屬性。
  • LoadFromDictionaries —— 從IDictionary<string, object>接口)載入資料到範圍中。 這在導入JSON資料時非常有用,並且附帶一個範例。
  • LoadFromArrays — 從[]載入資料到範圍中,每個物件陣列對應於工作表中的一行。

當使用這些方法時,您可以選擇傳遞參數以生成Excel表。 範例項目的範例4和5 Sample-.NET Framework包含更詳細的範例。

  • 寫入Excel文件

下一步,我們來看看是否可以將資料導出到新的Excel文件。

以下是一些我們想保存為Excel文件的樣本資料/物件。

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

為了使用基本資訊建立一個新的Excel文件,我們必須使用ExcelPackage類。 寫入資料到文件並生成新的Excel試算表只需幾行程式碼。 請注意下方的這一行,它執行將DataTables載入到Excel工作表的魔法。

Epplus Read Create Excel Alternative 6 related to EPPlusSoftware AB如何寫入Excel檔案

為了簡單起見,我在同一個項目資料夾中生成了一個新的試算表文件(Excel文件將在項目的'bin'資料夾中生成)。 源程式碼如下:

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

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

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

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

以下述API調用進行資料驗證後,將建立一個新的Excel文件,帶有上述自定義物件轉換為相應的Excel列和行,以顯示下方的值。

Epplus Read Create Excel Alternative 7 related to EPPlusSoftware AB如何寫入Excel檔案

上述現成的API可用於.NET Core控制台、測試項目或ASP.NET Core應用程式中,並且可以根據您的需要更改邏輯。

這些技術可以通過"cells"屬性(ExcelRange)存取:

  • ToText and ToTextAsync — 從範圍建立CSV字串。
  • 將範圍寫入CSV文件SaveToTextAsync
  • 使用ToDataTable方法將範圍中的資料導出到System中。 DataTable
  • GetValue — 顯示帶資料型別選項的值。
  • Value — 返回或設置範圍的值。

可以直接在工作表物件上使用SetValue方法。 (這將比在範圍上讀取/寫入得到略好的結果):

  • GetValue — 獲取單個單元格的值,可以選擇指定資料型別。
  • SetValue — 更改單個單元格的值。

Linq可以用來從工作表中查詢資料,因為單元格屬性實現了IEnumerable接口。

使用IronXL打開和寫入Office Open XML格式的XLSX

IronXL是一個.NET程式庫,允許C#開發者快速輕鬆地處理Excel、旋轉表和其他試算表文件。

不需要Office互操作。 在Core或Azure上沒有特定依賴性,也不需要安裝Microsoft Office。

IronXL是一個廣受好評的C#和VB.NET xl試算表程式庫,適用於.NET core和.NET framework。

  • 讀取Excel檔案
  • 要加载的工作表

Excel表由WorkBook類呈現。 我們利用WorkBook來讀取C#中的Excel文件,即使是旋轉表。 載入Excel文件並選擇其位置(.xlsx)。

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

工作簿中可以找到多個工作表物件。 這些是Excel文件中的工作表。 如果工作表包含工作表,使用GetWorkSheet找到它們。

var worksheet = workbook.GetWorkSheet("GDPByCountry");
var worksheet = workbook.GetWorkSheet("GDPByCountry");
Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
$vbLabelText   $csharpLabel
  • 建立自己的工作簿。

用工作表型別構造一個新的WorkBook以在記憶體中生成一個新的工作簿。

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

對於舊版Microsoft Excel試算表,請使用ExcelFileFormat.XLS(95及更早版本)。

如果您還沒有,請建立一個工作表。

每個"工作簿"中可以有多個"工作表"。一個"工作表"是一個資料表,而一個"工作簿"是多個"工作表"的集合。 在Excel中,一個具有兩個工作表的工作簿看起來是這樣的。

Epplus Read Create Excel Alternative 8 related to 使用IronXL打開和寫入Office Open XML格式的XLSX

WorkSheet的名稱。

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

傳遞工作表的名稱給CreateWorkSheet

獲取セルの範圍

"範圍"類表示一個二維"單元格"物件集合。 它表示特定的Excel單元格範圍。 使用工作表物件上的字串索引器,可以獲取範圍。

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

參數文字可以是單元格座標(例如,"A1")或從左到右、從上到下的一行單元格(例如,"B2:E5")。 從工作表也可以調用GetRange

  • 在一個範圍內,編輯單元格值

範圍內單元格的值可以通過多種方式讀取或編輯。 如果已知計數,請使用For迴圈。 您也可以從這裡進行單元格樣式設置。

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

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

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

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

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

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

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

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

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

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

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

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

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

驗證電子表格中的資料

要驗證資料表,請使用IronXL。 DataValidation範例驗證帶有libphonenumber-C#的電話號碼,以及使用傳統C# API的電子郵件地址和日期。

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

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

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

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

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

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

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

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

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

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

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

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

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

上面的程式碼迴圈遍歷電子表格的行,將單元格作爲列表抓取。每個驗證方法驗證單元格的值,並在值不正確時返回錯誤。

此程式碼建立一個新表、指定標題,並生成錯誤消息結果,以便可以保留不正確的資料日誌。

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

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

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

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

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

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

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

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

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

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

使用Entity Framework导出数据

使用IronXL將Excel試算表轉換爲資料庫或導出資料到資料庫。 ExcelToDB範例讀取包含按國家劃分的GDP的工作表並將其導出到SQLite。

它使用EntityFramework建立資料庫,然後逐行導出資料。

應安裝SQLite Entity Framework NuGet套件。

Epplus Read Create Excel Alternative 9 related to 使用IronXL打開和寫入Office Open XML格式的XLSX

您可以使用EntityFramework構建模型物件,以將資料導出到資料庫。

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

要使用不同的資料庫,請安裝適當的NuGet包,並查找UseSqlServer等)。

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

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

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

        var command = connection.CreateCommand();

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

        optionsBuilder.UseSqlite(connection);

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

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

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

        var command = connection.CreateCommand();

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

        optionsBuilder.UseSqlite(connection);

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

	Public Property Countries() As DbSet(Of Country)

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

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

		Dim command = connection.CreateCommand()

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

		optionsBuilder.UseSqlite(connection)

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

建立一個SaveChangesAsync將資料保存到資料庫中。

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

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

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

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

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

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

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

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

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

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

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

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

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

在電子表格中插入公式

可以使用Formula屬性設置單元格的公式

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

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

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

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

列C中的程式碼遍歷每個州並計算百分比總和。

可以將來自API的資料下載到電子表格

在下面的調用中使用RestClient.Net進行REST調用。 它下載JSON並將其轉換為RestCountry型"List"。然後可以通過遍歷每個國家輕鬆將來自REST API的資料保存到Excel文件中。

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

來自API的JSON資料如下所示:

Epplus Read Create Excel Alternative 10 related to 使用IronXL打開和寫入Office Open XML格式的XLSX

以下程式碼遍歷國家並使用名稱、人口、地區、數字程式碼和前三種語言填充電子表格。

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

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

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

        var language = country.languages[x];

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

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

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

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

        var language = country.languages[x];

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

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

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

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

		Dim language = country.languages(x)

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

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

使用IronXL打開Excel文件

啟動Excel文件後,增加前幾行讀取第一個工作表中的第1單元格並列印。

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

使用IronXL建立新的Excel文件。

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

之後,您可以使用各自的程式碼保存為CSV、JSON或XML,正如IronXL程式碼範例中所示。

例如,要保存為XML .xml

要保存為XML,請使用SaveAsXml如下:

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

結果如下所示:

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

IronXL提供了一個更簡潔的API來讀取Excel文件——存取工作簿中的列、行和單元格通常需要較少的程式碼行。 相比之下,EPPlus公開了更精細的單元級API,要求明確的列和行處理,提供精細控制但增加了冗長性。

IronXL在操作Excel文件時提供更廣泛的靈活性。 它支持在任何時間點建立附加工作表,在單次工作流程中跨多個工作表和工作簿讀取資料,並直接將工作簿資料導出到資料庫。 EPPlus專注於其API在處理個別工作表上的功能——對於單表任務而言簡單明瞭,但對於需要跨工作簿操作的團隊來說會產生其他整合步驟。

EPPlus和IronXL在授權和定價方面的比較如何?

EPPlus授權模型和價格

EPPlus可以在兩種授權模型下使用,無論是非商業授權模型還是來自Polyform的商業授權模型。

商業授權

這些授權有永久和訂閱兩種形式,期限從一個月到兩年不等。

在授權期間,所有授權類別均包含通過支援中心提供的支援和通過NuGet進行的升級。

EPPlus要求每個開發者擁有一個授權。 授權頒發給單個個人,不能共享。 作為一般準則,任何直接使用EPPlus進行程式碼開發或需要除錯程式碼的人員都應持有商業授權。

如果您內部提供EPPlus作為服務(例如,通過API公開其功能),您的公司必須購買一個涵蓋將使用該服務的內部使用者(開發者)數量的訂閱。

訂閱

您可以隨時使用最新版本的訂閱,但只要您使用EPPlus進行開發,就必須擁有有效的授權。 授權期結束時,授權會在付款完成後自動出單並續約。 您可以在每個授權期的末尾取消訂閱,並隨時開始新的訂閱。訂閱只能通過網路購買。

EPPlus可以在商業環境中使用。 該授權適用於每家公司的一位開發者,具有無限制的部署位置數量。 每年可購買的授權數量可以增加或減少,在每個年終時可以暫停或取消授權。

可以選擇32天的試用期。

價格:從每年$299開始。

隨用隨付

在單個組織內的每開發者價格,具有無限制的部署位置數量和Stripe開票功能。 每月可購買的授權數量可以增加或減少,在每個月末可以暫停或取消授權。

價格:從每月$29開始。

永久授權

永久授權允許您在設置的支持時間內更新到新版本和獲得支援。然後,您可以繼續使用此期間內發布的版本進行軟體開發,而無需續約授權。

在同一家公司內,每開發者的價格,具有無限部署網站。 無限期使用支持/升級期限內發布的所有EPPlus版本。

可以選擇32天的試用期。

價格:從每年$599開始。

套件

帶有初始升級和支持持續時間的永久授權選項可供選擇。 然後,您可以繼續使用在該時期內發布的版本開發軟體,而無需續約授權。

價格:從每年$4,295開始。

Polyform的非商業授權

EPPlus從5.0版開始按Polyform非商業授權進行授權,這表示程式碼是開源的,可以用於非商業用途。 你可以在他們的網站上看到更多細節。

IronXL授權模型和定價

永久授權:每個授權購買一次,不需續約。

免費支持和產品更新:每個授權都附帶一年的免費產品更新和產品背後的團隊提供的支持。 可以在任何時候購買擴展。 可以查看擴展。

即時授權:已註冊的授權密鑰會在收到付款后立即發送。

如果您對IronXL的.NET授權有任何疑問,請聯繫我們的Iron Software授權專家。

所有授權都是永久的,適用於開發、預備和生產環境。

Lite - 允許一個組織中的單個軟體開發人員在單個位置使用Iron Software。 Iron Software可以用在單個網頁應用程式、內聯應用程式或桌面軟體程式中。 許可證是不可轉讓的,並且不能在組織或機構/客戶關係之外共享。此許可型別與所有其他許可型別一樣,明確排除協議中未明確授予的所有權利,包括OEM再分發和使用Iron Software作為SaaS而不購買額外覆蓋。

價格:從$999開始。

專業授權 - 允許一個組織中指定數量的軟體開發者在單一地點使用Iron Software,最多可達十人。 Iron Software可以用在任何多個網站、內聯應用程式或桌面軟體應用程式中。許可證是不可轉讓的,並且不能在組織或機構/客戶關係之外共享。此許可型別與所有其他許可型別一樣,明確排除下在協議中未明確授予的所有權利,包括OEM再分發和使用Iron Software作為SaaS而不購買額外覆蓋。

價格:從$2,999開始。

無限授權 - 允許組織中的無限數量的軟體開發者在無限數量的地點使用Iron Software。 Iron Software可以用在任何多個網站、內聯應用程式或桌面軟體應用程式中。許可證是不可轉讓的,並且不能在組織或機構/客戶關係之外共享。此許可型別與所有其他許可型別一樣,明確排除下在協議中未明確授予的所有權利,包括OEM再分發和使用Iron Software作為SaaS而不購買額外覆蓋。

免版稅再分發 - 允許您根據基礎許可所涵蓋的專案數量將Iron Software作為多種不同的包裝商業產品的一部分進行分發(無需支付版稅)。 允許根據基礎許可涵蓋的專案數量在SaaS軟體服務中部署Iron Software。

價格:從$5,999開始。

除了授權成本,總專案成本包括用於編寫額外的導出邏輯(如JSON和XML格式)、構建手動資料庫整合管道以及管理本身不處理的多試算表協作的開發者工時。 對於評估多年專案生命週期成本的團隊來說,這些整合和維護成本往往會超過兩種授權模式之間的差異。

您應選擇哪個程式庫?

EPPlus提供了一個健全、成熟的API,可用於處理Office Open XML電子表格,其細粒度的單元級控制適用於需要精確工作表操作的項目。 對於要求擴展到多格式導出(XML、HTML、JSON)、跨工作簿操作和資料庫整合的團隊,IronXL將這些功能作爲一級操作新增。 IronXL還每次編輯文件時重新計算公式,並提供直觀的範圍語法與WorkSheet[“A1:B10”]。 單元格資料格式涵蓋文字、數字、公式、日期、貨幣、百分比、科學記數法和時間,而單元格樣式包括字體、大小、背景圖案、邊框和對齊。 可在範圍、列和行之間進對排序。 最終選擇取決於您的項目是否需要EPPlus專注的Open XML處理或IronXL的更廣泛的功能面。 要查看IronXL如何適合您的工作流程,下載免費30天的試用版,並在您自己的環境中測試本文中的範例。

請注意EPPlus是其各自拥有人的一個註冊商標。 本網站與EPPlus沒有聯繫,也未由其贊助或支持。 所有產品名稱、標誌和品牌均為其各自所有者的財產。 比較僅供資訊參考,反映了撰寫時公開可用的資訊。

常見問題

如何在不使用Microsoft Office的情況下建立Excel文件?

您可以使用IronXL來建立Excel文件,而不需要Microsoft Office。IronXL提供簡單的API,用於在C#和VB.NET中讀取、編輯和建立Excel試算表。

使用IronXL相對於EPPlus有哪些優勢?

IronXL提供更直觀的API,支持多種文件格式,如XML、HTML和JSON,並允許進行高級樣式設置和公式重新計算。這使得它對開發者而言比EPPlus更實用和靈活。

是否可以使用IronXL操作Excel資料並導出到不同的格式?

是的,IronXL支持將Excel資料導出為各種格式,如XML、HTML和JSON,使其易於與資料庫和其他應用程式整合。

如何使用IronXL處理Excel公式?

IronXL支持直觀的公式重新計算,這意味著每次編輯文件時,公式會自動更新,提供了一個高效的系統來管理Excel公式。

IronXL提供哪些授權選擇?

IronXL提供永久授權,適用於開發、測試和生產環境,價格從每年$489起,適用於單一開發者。它包括一年的免費更新和支援。

EPPlus可用於建立樞紐分析表並應用條件格式嗎?

是的,EPPlus支持建立樞紐分析表和應用條件格式,但比IronXL通常需要更複雜的程式碼。

IronXL如何支持跨平台開發?

IronXL支持包括.NET Core、.NET Framework、Xamarin、行動裝置、Linux、macOS和Azure在內的多個平台,使其適合跨平台開發。

IronXL需要在伺服器或客戶端機器上安裝Microsoft Office嗎?

不,IronXL不需要安裝Microsoft Office。它被設計為獨立於Office運作,提供讀取、編輯和建立Excel文件的功能。

EPPlus處理Excel文件的關鍵特徵是什麼?

EPPlus以其Office OpenXML支持而聞名,對於熟悉Excel的開發者來說易於使用,並具有建立樞紐分析表和應用條件格式的功能。它可用於雙重授權模式。

如何為我的.NET專案安裝IronXL?

您可以在NuGet程式包管理器控制台中使用指令Install-Package IronXL.Excel 安裝IronXL,或者使用.NET CLI指令dotnet add package IronXL.Excel

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話