跳過到頁腳內容
與其他組件的比較

IronXL 和 Epplus 的比較

本文將探討 IronXL 與 EPPlus 軟體的異同。

對大多數組織而言,微軟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。 或者,正如有人所說,"運用智能感知走向勝利!"

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,該程式庫也可用於處理 Excel 檔案。

IronXL 支援 .NET Core、.NET Framework、Xamarin、行動平台、Linux、macOS 和 Azure。

有很多不同的方法可以讀取和寫入電子表格中的資料。

使用 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 後,您可以進入表單並開始進行開發。

使用 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 檔案版本)格式的檔案。

-設定預設工作表

設定預設工作表就更簡單了:

// 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

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

程式碼本身很容易理解,並且有足夠的註解來幫助你理解各種處理過程。 但首先,讓我們快速回顧一下我們正在做的事情:

  • 使用自訂資料提供者方法,我們得到一個DataTable物件。
  • 我們建立了一個ExcelPackage對象,它是 EPPlus 用於 XLSX 檔案的主要容器。
  • 我們在ExcelPackage中新增一個ExcelWorksheet ,該工作表將用於輸入資料。
  • 為了建立標題行,我們遍歷DataTable列,並將它們新增到工作表的第一行。
  • 我們遍歷DataTable每一行,將每一行逐行加入到工作表中(從第 2 行開始),以便DataTable每一行都對應工作表中的一行。
  • DataTableExcelPackage轉換完成後,我們建立一個MemoryStream來儲存ExcelPackage二進位數據,然後將其轉換為位元組數組。
  • 我們建立 HTML 回應,並將 XLSX 檔案以 Content-Disposition 附件的形式傳送給用戶,使瀏覽器自動下載該檔案。

IronXL 在這個案例中勝出,因為創建過程非常簡單——你只需要一行程式碼即可完成; 這有助於節省時間,並且便於調試,而 EPPlus 提供的程式碼行枯燥乏味,難以閱讀和調試。

EPPlus Software AB 如何寫入 Excel 文件

EPPlus 支援處理 Excel 檔案。 這是一個用於讀取和寫入 Excel 檔案的 .net 程式庫。

-讀取 Excel 文件

為此,您需要先安裝 EPPlus 套件:前往"工具"->"NuGet 套件管理員"->"管理此解決方案的 NuGet"->"安裝 EPPlus"->"安裝 EPPlus"->"安裝 EPPlus"->"安裝 EPPlus"->"安裝 EPPlus"->"安裝 EPPlus"->"安裝 EPPlus" 。 在"瀏覽"標籤中搜尋"EPPlus",然後安裝 NuGet 套件。

Epplus Read Create Excel Alternative 4 related to EPPlus Software 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 EPPlus Software AB 如何寫入 Excel 文件

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

  • 使用LoadFromTextLoadFromTextAsync讀取 CSV 文字檔案並將資料載入到工作表的某個區域。
  • LoadFromDataReaderAsyncLoadFromDataReader — 將 DataReader 中的資料欄位載入到指定範圍內。
  • LoadFromDataTable — 將資料從DataTable載入到指定範圍內。 它可以從各種來源匯入數據,包括 XML(提供了一個範例)和資料庫。
  • LoadFromCollection — 反射地將IEnumerable中的資料載入到 range 中。
  • LoadFromCollection with attributes — 反射地將IEnumerable中的資料載入到範圍或表格中。 樣式、數字格式、公式和其他屬性均透過屬性指定。
  • LoadFromDictionaries — 從ExpandoObject /動態物件的IEnumerable載入資料(透過它們的IDictionary<string, object>IDictionary<string, object>接口)進入一個範圍。 這對於導入 JSON 資料非常有用,並且還附帶了一個範例。
  • LoadFromArrays — 將物件[]IEnumerable中的資料載入到指定範圍內,每個物件陣列對應於工作表中的一行。

使用這些方法時,您可以選擇性地提供一個參數來產生 Excel 表格。 範例專案Sample-.NET FrameworkSample-.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"
	}
}
$vbLabelText   $csharpLabel

要建立包含必要資訊的新 Excel 文件,我們必須使用ExcelPackage類別。 將資料寫入檔案並產生新的 Excel 電子表格只需要幾行程式碼。 請注意下面這行程式碼,它實作了將DataTables載入到 Excel 表格中的神奇功能。

Epplus Read Create Excel Alternative 6 related to EPPlus Software 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 EPPlus Software AB 如何寫入 Excel 文件

上述即用型 API 可用於 .NET Core 控制台、測試專案或 ASP.NET Core 應用程序,並且可以根據需要更改邏輯。

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

  • ToText 和 ToTextAsync — 從指定範圍建立 CSV 字串。
  • 使用SaveToTextSaveToTextAsync將範圍寫入 CSV 檔案。 -使用 ToDataTable 方法將某個範圍內的資料匯出到系統。 DataTable -獲取值— 顯示一個值,並可選擇資料類型。 -— 傳回或設定範圍的值。

GetValueSetValue方法也可以直接用於工作表物件。 (這會比在靶場上讀寫略微好一些):

-獲取值— 取得單一儲存格的值,並可選擇指定資料類型。

  • 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文件的工作表。 如果工作表包含工作表,請使用名稱WorkBook透過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 文件

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

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

將工作表名稱傳遞給CreateWorkSheet

取得蜂窩範圍

"Range"類別表示"Cell"物件的二維集合。 它表示Excel中的特定單元格區域。 使用 WorkSheet 物件上的字串索引器,可以取得範圍。

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

參數文字可以是單元格的座標(例如,"A1"),也可以是從左到右、從上到下的單元格範圍(例如,"B2:E5")。 GetRange也可以從工作表中呼叫。

-在指定範圍內,編輯儲存格值

可以透過多種方式讀取或編輯 Range 區域內單元格的值。 如果已知計數,請使用 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-CSharp 驗證電話號碼,並使用傳統的 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

使用實體框架導出數據

使用 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 套件,並尋找UseSqLite等效項( UseMySQLUseSqlServer等)。

/**
 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

產生一個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 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 類型的"清單"。然後,可以透過遍歷每個國家/地區,輕鬆地將來自 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 文件

以下程式碼循環遍歷各國,並將名稱、人口、地區、數位代碼和前 3 種語言填入電子表格中。

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 檔案後,新增讀取第一個工作表第一個儲存格的前幾行,然後列印。

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 格式。

例如,儲存為 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

與使用EPPlus相比,使用IronXL讀取Excel檔案更容易。 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 起。

Packages

提供永久授權選項,並包含一定期限的升級和支援服務。 在此期間,您可以繼續使用已發布的版本開發軟體,而無需續訂許可證。

定價:每年 $4,295 起。

Polyform的非商業許可

從版本 5 開始,EPPlus 採用 Polyform 非商業授權協議,這表示程式碼是開源的,可以用於非商業用途。 您可以在他們的網站上查看更多詳情。

IronXL 許可模式和價格

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

免費支援和產品更新:每個許可證都包含一年的免費產品更新和產品團隊提供的支援。 隨時都可以購買擴充功能。 可以查看擴充功能。

立即發放許可證:註冊許可證密鑰將在收到付款後立即發送。

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

所有許可均為永久性許可,適用於開發、測試和製作。

Lite - 允許組織中的單一軟體開發人員在一個地方使用 Iron 軟體。 Iron Software 可用於單一 Web 應用程式、內部網路應用程式或桌面軟體程式。 許可證不可轉讓,且不得在組織或代理/客戶關係之外共享。與其他所有授權類型一樣,此授權類型明確排除本協議未明確授予的所有權利,包括OEM再分發以及在未購買額外服務的情況下將Iron軟體作為SaaS使用。

定價:每年 $489 起。

專業許可證- 允許組織中預定數量的軟體開發人員在同一地點使用 Iron Software,最多可達十人。 Iron 軟體可用於任意數量的網站、內部網路應用程式或桌面軟體應用。許可證不可轉讓,且不得在組織或代理/客戶關係之外共享。與其他所有授權類型一樣,此授權類型明確排除本協議未明確授予的所有權利,包括 OEM 再分發以及在未購買額外服務的情況下將 Iron 軟體作為 SaaS 使用。

定價:每年 $976 起。

無限許可- 允許組織內無限數量的軟體開發人員在無限數量的地點使用 Iron Software。 Iron 軟體可用於任意數量的網站、內部網路應用程式或桌面軟體應用。許可證不可轉讓,且不得在組織或代理/客戶關係之外共享。與其他所有授權類型一樣,此授權類型明確排除本協議未明確授予的所有權利,包括 OEM 再分發以及在未購買額外服務的情況下將 Iron 軟體作為 SaaS 使用。

免版稅再分發- 允許您根據基本許可涵蓋的項目數量,將 Iron 軟體作為多個不同打包商業產品的一部分進行分發(無需支付版稅)。 允許在 SaaS 軟體服務中部署 Iron Software,部署數量取決於基本授權涵蓋的項目數量。

定價:每年 39 美元起。

結論

總而言之,IronXL 比 EPPlus 更實用,因為它能讓你根據需要靈活地在 Excel 表格中導航,程式碼行數更少,並且有更多匯出選項,包括 XML、HTML 和 JSON。 IronXL 還允許您將工作簿資料整合到資料庫中。 此外,它還具有直覺的系統,每次編輯文件時都會重新計算公式,並且提供了一個直觀的範圍設置,其語法為 WorkSheet["A1:B10"]。 工作表函數包含與 Excel 相容的公式,並且每次編輯工作表時都會重新計算。 單元格資料格式包含多種類型,包括文字、數字、公式、日期、貨幣、百分比、科學計數法和時間。它們的自訂格式具有不同的排序方法,例如按範圍、列和行排序。 它的單元格樣式包括各種字體、大小、背景圖案、邊框和對齊方式。

請注意EPPlus 為其各自所有者的註冊商標。 本網站與EPPlus沒有任何關聯,也未獲得EPPlus的認可或贊助。 所有產品名稱、標誌和品牌均為其各自擁有者的財產。 比較資料僅供參考,並反映撰寫時的公開資訊。

常見問題解答

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

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

與 EPPlus 相比,使用 IronXL 有哪些優勢?

IronXL 提供更直覺的 API,支援 XML、HTML 和 JSON 等多種檔案格式,並允許進階造型和公式重新計算。因此,相較於 EPPlus,它對開發人員而言更為實用和靈活。

是否可以使用 IronXL.Excel 處理 Excel 資料並將其匯出為不同格式?

是的,IronXL.Excel 支援將 Excel 資料匯出成各種格式,例如 XML、HTML 和 JSON,讓您輕鬆與資料庫和其他應用程式整合。

IronXL.Excel 如何處理 Excel 公式?

IronXL 支援直覺的公式重新計算,這表示每次編輯文件時,公式都會自動更新,提供一個有效率的 Excel 公式管理系統。

IronXL 提供哪些授權選項?

IronXL 為開發環境、暫存環境和生產環境提供永久授權,單一開發人員每年的定價從 489 美元起。它包括一年的免費更新和支援。

EPPlus 可以用來建立透視表和套用條件格式化嗎?

是的,EPPlus 支援建立資料透視表和套用條件格式,不過通常需要比 IronXL 更複雜的程式碼。

IronXL 如何支援跨平台開發?

IronXL 支援多種平台,包括 .NET Core、.NET Framework、Xamarin、Mobile、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 指令安裝 IronXL。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。