與其他組件比較

IronXL 與 Epplus 的比較

發佈 2022年3月23日
分享:

本文將探討IronXL和EPPlus軟體之間的相似點和差異。

對於大多數組織來說,Microsoft Excel已被證明是一個極為有用的工具。Excel文件,如數據庫,包含在單元格中的數據,簡單地使得需要存儲的數據易於管理。

Excel也使用.xls和.xlsx文件格式。使用C#語言來管理Excel文件可能會很困難。然而,IronXL和EPPlus軟體使這些過程變得更容易處理。

使用這些軟體時,不需要安裝Microsoft Office。

請注意,您可以在不安裝Microsoft Office的情況下,在C#中讀取和創建Excel文件。今天,我們將看看一些易於實施的不同選項。

什麼是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,請前往 視圖 > 其他視窗 > 套件管理器主控台,然後輸入以下命令:

PM> Install-Package EPPlus

如果您更喜歡使用 .NET CLI,請在提昇的命令提示符或 PowerShell 提示符下執行以下命令:

PM> dotnet add package EPPlus

EPPlus 是您可以添加到專案中的 dotnet 套件。

IronXL 是什麼?

IronXL 是一個簡單的 C# 和 VB Excel API,允許您以閃電般的速度在 .NET 中讀取、編輯和創建 Excel 試算表文件。不需要安裝 Microsoft Office 甚至 Excel Interop。此庫也可以用於處理 Excel 文件。

.NET Core、.NET Framework、Xamarin、Mobile、Linux、macOS 和 Azure 都受到 IronXL 的支持。

有多種不同的方法可以讀取和寫入試算表中的數據。

使用 NuGet 套件管理器新增 IronXL

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

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

使用以下命令在您的專案中開啟套件管理器主控台:

要存取套件管理器主控台,請移至 工具 => NuGet 套件管理器 => 套件管理器主控台。

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

PM > Install-Package IronXL.Excel

  • 使用 NuGet 套件管理器來安裝 IronXL

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

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

這將啟動 NuGet-Solution;選擇“瀏覽”並搜尋 IronXL。

在搜索欄中輸入 Excel:

當您點擊「安裝」按鈕時,將為您安裝 IronXL。安裝 IronXL 後,您可以進入您的表單並開始開發它。

使用 IronXL 建立 Excel 檔案

使用 IronXL 創建新的 Excel 工作簿變得非常簡單! 只需一行程式碼! 是的,這是真的:

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
VB   C#

IronXL 可以建立 XLS 文件 (較早的 Excel 文件版本) 和XLSX (目前和更新的 Excel 檔案版本) 格式。

  • 設置默認工作表

設置默認工作表更加容易:

var sheet = workbook.CreateWorkSheet
```(2020年度預算);

在以上代碼片段中,工作表被表示為 "Sheet",您可以用它設置單元格值並做幾乎所有Excel可以做的事情。您也可以將您的Excel文件編碼為只讀文件並執行刪除操作。 您還可以像Excel一樣鏈接您的工作表。

讓我澄清一下工作簿和工作表之間的區別,以防您不確定。

工作表包含在工作簿中。這意味著您可以在一個工作簿中放入任意多的工作表。我會在稍後的文章中解釋如何做到這一點。工作表由行和列構成。行和列的交集稱為單元格,這是您在Excel中將要互動的對象。

## 使用 Epplus Software AB 建立 Excel 檔案

EPPlus 可以用來建立 Excel 檔案並執行操作,例如建立樞紐分析表、樞紐範圍,甚至是條件格式化和字體變更。話不多說,以下是將普通的 DataTable 轉換為 XLSX Excel 檔案並發送給使用者下載的完整源代碼:

```cs
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 cols 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 colum names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows to 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);
}
var sheet = workbook.CreateWorkSheet
```(2020年度預算);

在以上代碼片段中,工作表被表示為 "Sheet",您可以用它設置單元格值並做幾乎所有Excel可以做的事情。您也可以將您的Excel文件編碼為只讀文件並執行刪除操作。 您還可以像Excel一樣鏈接您的工作表。

讓我澄清一下工作簿和工作表之間的區別,以防您不確定。

工作表包含在工作簿中。這意味著您可以在一個工作簿中放入任意多的工作表。我會在稍後的文章中解釋如何做到這一點。工作表由行和列構成。行和列的交集稱為單元格,這是您在Excel中將要互動的對象。

## 使用 Epplus Software AB 建立 Excel 檔案

EPPlus 可以用來建立 Excel 檔案並執行操作,例如建立樞紐分析表、樞紐範圍,甚至是條件格式化和字體變更。話不多說,以下是將普通的 DataTable 轉換為 XLSX Excel 檔案並發送給使用者下載的完整源代碼:

```cs
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 cols 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 colum names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows to 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);
}
Dim sheet = workbook.CreateWorkSheet ```(2020年度預算)

## 使用 Epplus Software AB 建立 Excel 檔案
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'在以上代碼片段中,工作表被表示為 "Sheet",您可以用它設置單元格值並做幾乎所有Excel可以做的事情。您也可以將您的Excel文件編碼為只讀文件並執行刪除操作。 您還可以像Excel一樣鏈接您的工作表。 讓我澄清一下工作簿和工作表之間的區別,以防您不確定。 工作表包含在工作簿中。這意味著您可以在一個工作簿中放入任意多的工作表。我會在稍後的文章中解釋如何做到這一點。工作表由行和列構成。行和列的交集稱為單元格,這是您在Excel中將要互動的對象。 EPPlus 可以用來建立 Excel 檔案並執行操作,例如建立樞紐分析表、樞紐範圍,甚至是條件格式化和字體變更。話不多說,以下是將普通的 DataTable 轉換為 XLSX Excel 檔案並發送給使用者下載的完整源代碼: ```cs public ActionResult ConvertToXLSX()
'{
'	byte [] fileData = Nothing;
'
'	' 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 cols 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 colum names
'			row = 1;
'			col = 0;
'			foreach (DataColumn dc in dt.Columns)
'			{
'				col++;
'				ws.SetValue(row, col, dc.ColumnName);
'			}
'
'			' Insert the DataTable rows to 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);
'}
VB   C#

如您所見,這是一個可以用於任何 ASP.NET MVC 控制器的 ActionResult 方法;如果您沒有使用 ASP.NET MVC,只需複製方法內容並粘貼到您需要的地方即可。 (經典 ASP.NET、控制台應用程式、Windows Forms,等等)這段程式碼淺顯易懂,有足夠的註釋幫助你理解各種處理過程。但首先,我們來快速回顧一下我們在這裡做什麼:

  • 使用自定義的資料提供者方法,我們獲取一個DataTable對象。
  • 我們構建一個ExcelPackage對象,這是EPPlus對XLSX文件的主要容器。
  • 我們向ExcelPackage添加一個ExcelWorksheet,這將是數據輸入的工作表。
  • 為了創建標題行,我們遍歷DataTable的列,將它們添加到工作表的第一行。
  • 我們遍歷DataTable的行,一行一行地將每一行數據添加到工作表中。 (從第2行開始) 使每個DataTable行對應一個工作表行。
  • 當DataTable轉換為ExcelPackage完成後,我們構建一個MemoryStream來存儲ExcelPackage二進制數據,然後將其轉換為字節數組。
  • 我們創建HTML答案,並使用Content-Disposition附件將XLSX文件發送給用戶,讓瀏覽器自動下載該文件。

在這種情況下,IronXL勝出,因為創建過程非常簡單——只需要一行代碼,你就完成了;這有助於節省時間和調試,而EPPlus提供的代碼行既無聊又難以調試。

EPPlus Software AB 如何編寫 Excel 檔案

EPPlus 支援 Excel 檔案的操作。它是一個讀寫 Excel 檔案的 .NET 函式庫。

  • 讀取 Excel 檔案

若要這樣做,您需要先安裝 EPPlus 套件:前往 "工具" -> "NuGet 套件管理員" -> "管理這個解決方案的 NuGet 套件" -> "安裝 EPPlus" -> "安裝 EPPlus" -> "安裝 EPPlus" -> "安裝 EPPlus" -> "安裝 EPPlus" -> "安裝 EPPlus" -> 安裝 EP 在「瀏覽」標籤中搜尋 "EPPlus",然後安裝該 NuGet 套件。

您可以在安裝套件後,將以下代碼用於您的控制台應用程序 "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
VB   C#

以下是一個帶有範例 Excel 檔案的主控台應用程式輸出範例 (.xlsx) 我們正在處理的。這是一個使用 EPPlus 在 C# 中進行讀取的 xlsx 文件。

可以使用 "cells" 屬性以下列方式從多個來源加載數據 (ExcelRange)- 讀取 CSV 文本文件,並使用 LoadFromText 和 LoadFromTextAsync 將數據載入到工作表中的範圍。

  • LoadFromDataReaderAsync 和 LoadFromDataReader — 從 DataReader 中載入數據域到範圍。
  • LoadFromDataTable — 從 DataTable 中載入數據到範圍。它可以從多種來源導入數據,包括 XML (提供了一個範例) 和資料庫。
  • LoadFromCollection — 反射性地從 IEnumerable 將資料載入到一個範圍內。
  • LoadFromCollection with attributes — 反射性地從 IEnumerable 將資料載入到一個範圍或表格中。樣式、數字格式、公式和其他屬性透過 attributes 指定。
  • LoadFromDictionaries — 從 IEnumerable 的 ExpandoObject/dynamic objects 中載入資料 (透過其IDictionary<string, object>接口) 轉換成範圍。這對匯入 JSON 數據非常有用,並且包含了一個範例。
  • LoadFromArrays — 從物件的 IEnumerable 加載數據 [] 轉換為範圍,每個對象數組對應工作表中的一行。

使用這些方法時,您可以選擇給出一個參數來生成 Excel 表格。在範例專案 Sample-.NET Framework 或 Sample-.NET Framework 的範例 4 和範例 5 中包含了更詳細的範例。

  • 寫入 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"
	}
}
VB   C#

要創建包含基本信息的新的 Excel 文件,我們必須使用 ExcelPackage 類。只需幾行代碼即可將數據寫入文件並生成新的 Excel 試算表。請注意以下這行,它實現了將 DataTables 加載到 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
VB   C#

在進行上述的資料驗證 API 呼叫之後,一個新的 Excel 檔案將會被創建,並將上述自定物件轉換成適當的 Excel 欄與列,以顯示以下的數值。

上述即用型API可以用於.NET Core控制台、測試項目或ASP.NET Core應用程式,且可根據您的需求變更邏輯。

這些技術可以通過 "cells" 屬性訪問。 (ExcelRange)- ToText 和 ToTextAsync — 從範圍建立 CSV 字串。

  • 使用 SaveToText 和 SaveToTextAsync 將範圍寫入 CSV 文件。
  • 使用 ToDataTable 方法將範圍中的數據匯出到 System.Data.DataTable。
  • GetValue— 顯示具有資料類型選項的值。
  • Value — 返回或設置範圍的值。

GetValue 和 SetValue 方法也可以直接在工作表對象上使用。 (這將提供比範圍讀寫稍微更好的結果):

  • GetValueT> — 獲取單個儲存格的值,可以指定數據類型。
  • SetValue — 更改單個儲存格的值。

由於儲存格屬性實現了 IEnumerable 介面,可以使用 Linq 從工作表中查詢數據。

使用 IronXL 開啟和撰寫 Office Open XML 格式的 XLSX

IronXL 是一個 .NET 函式庫,可讓 C# 開發人員快速且輕鬆地處理 Excel、樞紐分析表和其他試算表文件。

不需要使用 Office Interop。也沒有特定依賴性或需要在 Core 或 Azure 上安裝 Microsoft Office。

IronXL 是一個知名的 .NET core 和 .NET framework 的 C# 和 VB.NET xl 試算表函式庫。

  • 讀取 Excel 文件
  • 載入工作表

一個 Excel 工作表由 WorkBook 類別表示。我們利用 WorkBook 在 C# 中打開包含樞紐分析表的 Excel 文件。載入 Excel 文件並選擇其位置。 (.xlsx).

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
'''
'''Load WorkBook
'''anchor-load-a-workbook
'''*
Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
VB   C#

工作表物件可以在許多工作簿中找到。這些是 Excel 文件的工作表。如果該表包含工作表,請使用名稱 WorkBook 來找到它們。GetWorkSheet。

var worksheet = workbook.GetWorkSheet("GDPByCountry");
var worksheet = workbook.GetWorkSheet("GDPByCountry");
Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
VB   C#
  • 製作您自己的工作簿。

建立一個新的WorkBook,其中包含生成新WorkBook所需的表類型,並在記憶體中生成。

/**
Create WorkBook
anchor-create-a-workbook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
/**
Create WorkBook
anchor-create-a-workbook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
'''
'''Create WorkBook
'''anchor-create-a-workbook
'''*
Dim workbook As New WorkBook(ExcelFileFormat.XLSX)
VB   C#

對於復古的 Microsoft Excel 試算表,請使用 ExcelFileFormat.XLS (95 及以前).

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

每個“工作簿”中可以有多個工作表。“工作表”是一個單一的數據表,而“工作簿”是一組工作表。在Excel中,這是一個包含兩個工作表的工作簿的外觀。

WorkBook 是您可以建立的新 WorkSheet 的名稱。

var worksheet = workbook.CreateWorkSheet("Countries");
var worksheet = workbook.CreateWorkSheet("Countries");
Dim worksheet = workbook.CreateWorkSheet("Countries")
VB   C#

將工作表的名稱傳遞給 CreateWorkSheet。

取得單元格範圍

“Range” 類表示“Cell” 對象的二維集合。 它表示特定範圍的 Excel 單元格。 使用 WorkSheet 對象上的字符串索引器,您可以獲取範圍。

var range = worksheet ["D2:D101"];
var range = worksheet ["D2:D101"];
Dim range = worksheet ("D2:D101")
VB   C#

參數文字可以是儲存格的座標 (例如,“A1”) 或從左到右、從上到下的單元格範圍 (例如 "B2:E5")。可以從工作表中調用 GetRange。

  • 在範圍內編輯單元格值

範圍內單元格的值可以通過各種方式讀取或編輯。如果已知計數,可以使用 For 循環。您還可以在此處進行單元格樣式設置。

/**
Edit Cell Values in Range
anchor-edit-cell-values-within-a-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
anchor-edit-cell-values-within-a-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
'''anchor-edit-cell-values-within-a-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
VB   C#

驗證試算表中的數據

要驗證一張數據表,請使用 IronXL。DataValidation 範例使用 libphonenumber-CSharp 驗證電話號碼,並使用傳統的 C# API 驗證電子郵件地址和日期。

/**
Validate Spreadsheet Data
anchor-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
anchor-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
'''anchor-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
VB   C#

上述程式碼會循環遍歷電子表格的行,將其單元格作為列表抓取。每個已驗證的方法會驗證單元格的值,如果值不正確則返回錯誤。

這段程式碼會創建一個新工作表,指定標題,並生成錯誤訊息結果,以便可以保留不正確的數據記錄。

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")
VB   C#

使用 Entity Framework 导出数据

使用 IronXL 将 Excel 电子表格转换为数据库或将数据导出到数据库。ExcelToDB 示例读取包含各国 GDP 的电子表格并将其导出到 SQLite。

它通过 EntityFramework 创建数据库,然后逐行导出数据。

应安装 SQLite Entity Framework NuGet 包。

您可以使用 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
VB   C#

要使用不同的數據庫,請安裝相應的NuGet軟體包並查找等效的UseSqLite。 ().

/**
Export Data using Entity Framework
anchor-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
anchor-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
'''anchor-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
VB   C#

生成一個 CountryContext,然後遍歷該範圍以創建每個條目,再用 SaveAsync 保存數據到數據庫。

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
VB   C#

在電子表格中加入公式

可以使用 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
VB   C#

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

來自 API 的數據可以下載到電子表格

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

/**
Data API to Spreadsheet
anchor-download-data-from-an-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
anchor-download-data-from-an-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
'''anchor-download-data-from-an-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))()
VB   C#

從 API 獲取的 JSON 數據如下:

以下程式碼遍歷各個國家,並將名稱、人口、地區、數字代碼和前三大語言填入試算表。

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
VB   C#

使用 IronXL 開啟 Excel 文件

在啟動 Excel 文件後,添加前幾行代碼以讀取第一個表格中的第一個單元格,並打印。

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
VB   C#

使用 IronXL,創建一個新的 Excel 文件。

/**
Create Excel File
anchor-create-a-new-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
anchor-create-a-new-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
'''anchor-create-a-new-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
VB   C#

之後,您可以使用各自的代碼將內容保存為CSV、JSON或XML。

例如,保存為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")
VB   C#

結果如下所示:

<?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 讀取 Excel 文件比使用 EPPlus 簡單得多。IronXL 擁有更多精簡的程式碼,涵蓋所有訪問工作簿中的所有列、行和單元格的需求,而使用 EPPlus 則需要特定的程式碼來讀取列和行。

IronXL 在操作 Excel 文檔方面更智能。它讓您能夠在任何時間點創建更多工作表,並從多個工作表和工作簿中讀取數據,而 EPPlus 一次只處理一個工作表。使用 IronXL,您還可以將 Excel 工作簿中的數據填入數據庫。

EPPlus 和 IronXL 授權及定價

EPPlus 授權模式和價格

EPPlus 可以在兩種授權模式下使用,分別是非商業授權模式或來自 Polyform 的商業授權模式。

商業授權

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

在所有授權類別中的授權期間內,通過支援中心進行支援,並通過 NuGet 進行升級。

EPPlus 每位開發人員需要一個授權。授權發給單一個人,不能共享。一般來說,任何產生或需要調試直接使用 EPPlus 的代碼的人都應該擁有商業授權。

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

訂閱

您可以訂閱獲取最新版本,但在使用EPPlus進行開發時必須持有有效的授權。在授權期限結束時,授權將自動開具發票並在付款後續約。您可以在授權期限結束時取消訂閱,並隨時重新訂閱。訂閱僅可透過網路購買。

EPPlus可以在商業環境中使用。授權是針對每家公司一位開發人員,且可部署到無限數量的位置。每年可購買的授權數量可以增加或減少,並且授權可以在每年結束時暫停或取消。

提供32天的試用期選項。

價格: 每年起價$299。

按需付款

單一組織內每位開發人員的價格,具有無限的部署位置和Stripe發票。每月可購買的授權數量可以增加或減少,並且授權可以在每月結束時暫停或取消。

價格: 每月起價$29。

永久授權

永久授權允許您在設定的時間內更新到新版本並獲得支持。然後,您可以在不需要續約的情況下繼續使用在此期間發布的版本進行軟體開發。

在同一公司內,每位開發人員的價格以及無限的部署位置。無限期使用在支持/升級期限內發布的所有EPPlus版本。

提供32天的試用期選項。

價格: 每年起價$599。

套裝

提供具有初始升級和支援期限的永久授權選項。然後,您可以在此期間發布的版本上繼續開發軟體,而不需要續約。

價格: 每年起價$4295。

Polyform的非商業授權

從版本5開始,EPPlus已獲得Polyform非商業授權,這表示程式碼是開放源碼的,可以用於非商業用途。您可以在他們的網站上查看更多詳細信息。

IronXL 授權模式與價格

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

免費支援及產品更新:每個授權皆附帶一年的免費產品更新和來自產品背後團隊的支援。隨時可以購買延長服務。可以查看延長服務方案。

即時授權:註冊授權碼在收到付款後立即發送。

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

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

Lite - 允許組織中的單個軟體開發人員在一個地方使用 Iron Software。Iron Software 可以用於單一網頁應用程式、內聯網應用程式或桌面軟體程式。授權不可轉讓,且不能分享給組織外部或是代理商/客戶關係之外的任何人。這種授權類型,如同所有其他授權類型一樣,明確排除所有未在協議中明確授權的權利,包括 OEM 重新分發和在未購買額外覆蓋的情況下作為 SaaS 使用 Iron Software。

價格: 每年起價 $489。

Professional License - 允許組織中預定數目的軟體開發人員在單一地點使用 Iron Software,最多可達十人。Iron Software 可以用於任意數量的網站、內聯網應用程式或桌面軟體程式。授權不可轉讓,且不能分享給組織外部或是代理商/客戶關係之外的任何人。這種授權類型,如同所有其他授權類型一樣,明確排除所有未在協議中明確授權的權利,包括 OEM 重新分發和在未購買額外覆蓋的情況下作為 SaaS 使用 Iron Software。

價格: 每年起價 $976。

Unlimited License - 允許組織中無限數量的軟體開發人員在無限數量的地點使用 Iron Software。Iron Software 可以用於任意數量的網站、內聯網應用程式或桌面軟體程式。授權不可轉讓,且不能分享給組織外部或是代理商/客戶關係之外的任何人。這種授權類型,如同所有其他授權類型一樣,明確排除所有未在協議中明確授權的權利,包括 OEM 重新分發和在未購買額外覆蓋的情況下作為 SaaS 使用 Iron Software。

免版稅重新分發 - 允許您將 Iron Software 作為不同包裝的商業產品的一部分進行分發 (無需支付版稅) 基於基礎授權所覆蓋的專案數量。允許在SaaS軟體服務中部署Iron Software,基於基礎授權所覆蓋的專案數量。

價格: 每年起價$2939起。

結論

總之,IronXL 比 EPPlus 更實用,因為它讓您能夠以更短的代碼行和更多的導出選項(包括 XML、HTML 和 JSON)靈活地瀏覽 Excel 表格。IronXL 還允許您將工作簿數據整合到數據庫中。此外,它具備一個直觀的系統,每次編輯文檔時會重新計算公式,並且提供一個直觀的範圍設置與工作表。 [“A1:B10”] 語法。工作表功能包括與Excel一起工作的公式,並在每次編輯工作表時重新計算。單元格數據格式包括多種文本、數字、公式、日期、貨幣、百分比、科學計數法和時間。其自定格式具有不同的排序方法,如範圍、列和行。單元格樣式包括各種字體、大小、背景圖案、邊框和對齊方式。

< 上一頁
IronXL 和 Aspose Cells 的比較
下一個 >
IronXL 和 Microsoft Office Interop Excel 的比較

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,023,839 查看許可證 >