跳過到頁腳內容
.NET幫助

Datatables .NET(開發者的工作原理)

ASP.NET 開發人員通常會尋求有效率的方式來呈現具排序、搜尋和分頁等進階功能的表格資料或 HTML 表格。 DataTables.NET是一個功能強大的 jQuery、JavaScript 函式庫和高度彈性的工具,可協助在網頁應用程式中建立互動且功能豐富的表格。 在這篇文章中,我們將探討如何將 DataTables.NET 分佈檔案 (一種用於伺服器端處理的表格增強函式庫) 整合到 ASP.NET 專案中,以增強表格資料的呈現和使用者體驗。

如何在 ASP.NET Web 應用程式中使用 DataTables?

1.建立 ASP.NET 網路應用程式 2.新增 DataTables 客戶端造型套件 3.安裝 Entity Framework 核心套件,只有核心軟體 4.新增模型類別、控制器和 Razor 頁面 5.在 JS 檔案中加入 JavaScript 程式碼 6.設定組態 7.建立並執行程式 8.使用 IronXL for Excel Data Export 將資料匯出到 Excel 檔案中

什麼是 DataTables.NET?

DataTables.NET 是一個 jQuery JavaScript 函式庫,可讓您在 .NET 應用程式中建立和操作互動式表格。 它以 jQuery DataTables 外掛程式為基礎,提供全面的 API 功能,例如動態和靜態 HTML 表格的分頁、排序、篩選和捲動。 這是一個表格增強函式庫,可與各種資料來源搭配使用,例如 SQL 資料庫、AJAX 或記憶體物件。

伺服器端處理

考慮一種情況,您有一個 API 端點,提供大量的產品資料集。 標準的方法包括 jQuery DataTables 對此 API 進行 AJAX 呼叫,取得 JSON 格式的產品清單,並呈現 HTML 表格。 這就是所謂的用戶端處理,對於較小的資料集(通常在 100 到 1000 條記錄之間)來說是有效率的。 然而,當資料集擴大到 10,000 條記錄或更多時,該怎麼辦?

在處理大量記錄時,一次過將整個資料集傳送至瀏覽器變得不切實際。 一次傳送 10,000 條記錄不僅浪費頻寬,也會造成瀏覽器資源緊張。 在這種情況下,另一種方法,即伺服器端處理,對於最佳化效能變得至關重要。

在伺服器端處理中,API 並非傳送整個資料集,而是以可管理的小塊傳送資料,通常每頁約有 50 條記錄。 這樣做之後,載入時間會大幅改善,因為 jQuery DataTables 現在只會載入適量的記錄 (~50) 而不是一次處理整個資料集。 此方法可減少 CPU 和頻寬的使用,在 API 和 DataTable 之間建立更有效率的互動。

在本文中,我們將探討在 ASP.NET Razor Page 應用程式中執行伺服器端處理,示範如何有效率地處理和顯示廣泛的資料集,同時提升 Web 應用程式的整體效能。

在 ASP.NET 8 中開始使用 DataTables.NET

要開始使用,我們需要將 DataTables.NET Client Side Library 加入專案中。 本文將使用 .NET 8 的 ASP.NET Core Web App (Razor Pages) 專案。您可以根據需求使用任何 Web App 專案。

若要新增用戶端函式庫,請在解決方案>新增>用戶端函式庫上按一下滑鼠右鍵,然後搜尋資料表,如下所示。

DataTables.NET (How It Works For Developer):圖 1 - 新增用戶端函式庫

現在,我們需要新增模型類別、DB Context、控制器、HTML 表格和 AJAX Call。

但在此之前,我們需要先安裝 EntityFramework NuGet 套件,以連結我們的應用程式與資料庫。 本文將使用 Code First Approach,您也可以依您的偏好使用 Database First。

安裝下列本機託管套件:

1.Microsoft.EntityFrameworkCore 2.Microsoft.EntityFrameworkCore.Design 3.Microsoft.EntityFrameworkCore.SqlServer 4.Microsoft.EntityFrameworkCore.Tools

使用 NuGet Package Manager Console 中的 install-package 指令安裝上述套件,或從 NuGet Package Manager 解決方案中搜尋安裝。

新增模型類別

我在本範例中使用 Product Model Class,您可以依據需求使用。

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
Public Class Product
	Public Property Id() As Integer
	Public Property ProductName() As String = String.Empty
	Public Property ProductPrice() As String = String.Empty
	Public Property ProductWeight() As String = String.Empty
	Public Property ProductDescription() As String = String.Empty
	Public Property ProductManufacturingDate() As DateTime
	Public Property ProductExpiryDate() As DateTime
End Class
$vbLabelText   $csharpLabel

新增 ApplicationDBContext 類別

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
Public Class ApplicationDBContext
	Inherits DbContext

	Public Sub New(ByVal options As DbContextOptions(Of ApplicationDBContext))
		MyBase.New(options)
	End Sub
	Public Property Products() As DbSet(Of Product)
End Class
$vbLabelText   $csharpLabel

新增進階互動控制

我們將在 wwwroot/js 資料夾內新增 ProductDatatables.js 以加入進階控制項,例如分頁、搜尋等。

// Initialize the DataTables plugin for the HTML element with 'productDatatable' ID
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true, // Enable processing indicator
        "serverSide": true, // Enable server-side processing
        "ajax": {
            "url": "/api/Product", // API endpoint for fetching product data
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            // Define properties for columns
            "targets": [0],
            "visible": false, // Hide the 'Id' column
            "searchable": false // Disable searching for the 'Id' column
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                // Add a 'Delete' button with an onclick event for deleting the product
                "render": function (data, type, row) { 
                    return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "');>Delete</a>"; 
                }
            }
        ]
    });
});
// Initialize the DataTables plugin for the HTML element with 'productDatatable' ID
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true, // Enable processing indicator
        "serverSide": true, // Enable server-side processing
        "ajax": {
            "url": "/api/Product", // API endpoint for fetching product data
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            // Define properties for columns
            "targets": [0],
            "visible": false, // Hide the 'Id' column
            "searchable": false // Disable searching for the 'Id' column
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                // Add a 'Delete' button with an onclick event for deleting the product
                "render": function (data, type, row) { 
                    return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "');>Delete</a>"; 
                }
            }
        ]
    });
});
JAVASCRIPT

現在,我們需要新增 HTML 表格。

新增 HTML 表格

index.cshtml 檔案中寫入下列程式碼,以新增靜態 HTML 頁面。

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product Name</th>
                    <th>Product Price</th>
                    <th>Product Weight</th>
                    <th>Product Description</th>
                    <th>Product Manufacturing Date</th>
                    <th>Product Expiry Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

@section Scripts {
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/js/ProductDatatable.js"></script>
}

我們需要加入控制器。

新增產品控制器

新增用於建立端點和直接拉取請求的 Product Controller。

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }

    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form["draw"].FirstOrDefault();
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToLis();

            // Filtering data based on provided search value
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)
                                            || m.ProductDescription.Contains(searchValue)
                                            || m.Id.ToString().Contains(searchValue)).ToList();
            }

            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception)
        {
            throw;
        }
    }
}
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }

    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form["draw"].FirstOrDefault();
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToLis();

            // Filtering data based on provided search value
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)
                                            || m.ProductDescription.Contains(searchValue)
                                            || m.Id.ToString().Contains(searchValue)).ToList();
            }

            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception)
        {
            throw;
        }
    }
}
<Route("api/[controller]")>
<ApiController>
Public Class ProductController
	Inherits ControllerBase

	Private ReadOnly context As ApplicationDBContext
	Public Sub New(ByVal context As ApplicationDBContext)
		Me.context = context
	End Sub

	<HttpPost>
	Public Function GetProducts() As IActionResult
		Try
			Dim draw = Request.Form("draw").FirstOrDefault()
			Dim start = Request.Form("start").FirstOrDefault()
			Dim length = Request.Form("length").FirstOrDefault()
			Dim searchValue = Request.Form("search[value]").FirstOrDefault()
			Dim pageSize As Integer = If(length IsNot Nothing, Convert.ToInt32(length), 0)
			Dim skip As Integer = If(start IsNot Nothing, Convert.ToInt32(start), 0)
			Dim recordsTotal As Integer = 0
			Dim productData = context.Products.ToLis()

			' Filtering data based on provided search value
			If Not String.IsNullOrEmpty(searchValue) Then
				productData = productData.Where(Function(m) m.ProductName.Contains(searchValue) OrElse m.ProductDescription.Contains(searchValue) OrElse m.Id.ToString().Contains(searchValue)).ToList()
			End If

			recordsTotal = productData.Count()
			Dim data = productData.Skip(skip).Take(pageSize).ToList()
			Dim jsonData = New With {
				Key .draw = draw,
				Key .recordsFiltered = recordsTotal,
				Key .recordsTotal = recordsTotal,
				Key .data = data
			}
			Return Ok(jsonData)
		Catch e1 As Exception
			Throw
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel

在此,我們在伺服器端實施了分頁與搜尋功能。

現在,我們需要設定資料庫,並將組態加入 Program.cs class。 如果您使用的是 .NET 5 或更低的版本,您可能需要在 Startup.cs class 中進行。

首先,在 appsettings.json 檔案中加入下列 Connection String。

"ConnectionStrings": {
   "ProductDB": "Server=localserver\\SQLEXPRESS;Database=ProductDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
}

現在將下列程式碼新增至 Program.cs class。

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<ApplicationDBContext>(options =>
    {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
    });
    builder.Services.AddControllers();
    // Add services to the container.
    builder.Services.AddRazorPages();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days.
         app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();
    app.MapRazorPages();
    app.Run();
}
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<ApplicationDBContext>(options =>
    {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
    });
    builder.Services.AddControllers();
    // Add services to the container.
    builder.Services.AddRazorPages();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days.
         app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();
    app.MapRazorPages();
    app.Run();
}
Public Shared Sub Main(ByVal args() As String)
	Dim builder = WebApplication.CreateBuilder(args)
	builder.Services.AddDbContext(Of ApplicationDBContext)(Sub(options)
		 options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"))
	End Sub)
	builder.Services.AddControllers()
	' Add services to the container.
	builder.Services.AddRazorPages()
	Dim app = builder.Build()
	' Configure the HTTP request pipeline.
	If Not app.Environment.IsDevelopment() Then
		 app.UseExceptionHandler("/Error")
		 ' The default HSTS value is 30 days.
		 app.UseHsts()
	End If
	app.UseHttpsRedirection()
	app.UseStaticFiles()
	app.UseRouting()
	app.UseAuthorization()
	app.MapControllers()
	app.MapRazorPages()
	app.Run()
End Sub
$vbLabelText   $csharpLabel

我們需要執行遷移,因為我們採用的是代碼先行的方法。

在套件管理員控制台執行下列指令。

Add-Migration init
Add-Migration init
SHELL

上述指令將建立轉換。 現在我們需要將這些轉換套用到資料庫中。 在套件管理員控制台執行下列指令。

Update-Database
Update-Database
SHELL

上述指令將在我們的資料庫中建立資料表。 在產品表格中加入虛擬資料; 您可以從 Mockaroo 產生隨機資料。

現在,建立並執行此應用程式。

輸出

我們可以看到,我們有一個非常互動的 UI,具有先進的互動控制。

DataTables.NET (How It Works For Developer):圖 2 - 輸出

現在,在伺服器端實施分頁,如下所示。

DataTables.NET (How It Works For Developer):圖 3 - 分頁

輸出 UI

然後在用戶端以豐富的 UI 控制渲染資料。

DataTables.NET (How It Works For Developer):圖 4 - UI

您可以按一下 explore DataTables.NET documentation 來探索 DataTables.NET 文件中的更多內容。

IronXL 簡介

IronXL - Excel Library for .NET 是一個可讓您在 .NET 應用程式中處理 Excel 檔案的函式庫。 它可以 建立 Excel 試算表讀取 CSV 檔案編輯 Excel 檔案,以及 以各種格式匯出至 Excel,例如 XLS、XLSX、CSV 和 TSV。它不需要安裝 Microsoft Office 或 Excel Interop。 它支援 .NET 8、7、6、5、Core、Framework 和 Azure。

我們經常需要將資料匯出成 Excel 或 CSV 檔案。 IronXL 是這種情況下的最佳選擇。 現在,我們要寫一段程式碼,將資料匯出到 Excel 檔案。

安裝 IronXL

在套件管理員控制台輸入以下指令,在我們的專案中安裝 IronXL 函式庫。

Install-Package IronPdf

這將會在我們的專案中安裝 IronXL 和所需的相依性。

將資料匯出至 Excel

讓我們寫一段程式碼,將產品清單轉換成 Excel 檔案。

public void ExportToExcel(List<Product> productList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Create a new workbook instance
    WorkSheet ws = wb.DefaultWorkSheet; // Access the default worksheet
    int rowCount = 1;

    // Iterate over the product list and fill the worksheet
    foreach (Product product in productList)
    {
        ws["A" + rowCount].Value = product.Id.ToString();
        ws["B" + rowCount].Value = product.ProductName;
        ws["C" + rowCount].Value = product.ProductDescription;
        ws["D" + rowCount].Value = product.ProductPrice;
        ws["E" + rowCount].Value = product.ProductWeight;
        ws["F" + rowCount].Value = product.ProductManufacturingDate;
        ws["G" + rowCount].Value = product.ProductExpiryDate;
        rowCount++;
    }
    wb.SaveAs("product.xlsx"); // Save the workbook as an Excel file
}
public void ExportToExcel(List<Product> productList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Create a new workbook instance
    WorkSheet ws = wb.DefaultWorkSheet; // Access the default worksheet
    int rowCount = 1;

    // Iterate over the product list and fill the worksheet
    foreach (Product product in productList)
    {
        ws["A" + rowCount].Value = product.Id.ToString();
        ws["B" + rowCount].Value = product.ProductName;
        ws["C" + rowCount].Value = product.ProductDescription;
        ws["D" + rowCount].Value = product.ProductPrice;
        ws["E" + rowCount].Value = product.ProductWeight;
        ws["F" + rowCount].Value = product.ProductManufacturingDate;
        ws["G" + rowCount].Value = product.ProductExpiryDate;
        rowCount++;
    }
    wb.SaveAs("product.xlsx"); // Save the workbook as an Excel file
}
Public Sub ExportToExcel(ByVal productList As List(Of Product))
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX) ' Create a new workbook instance
	Dim ws As WorkSheet = wb.DefaultWorkSheet ' Access the default worksheet
	Dim rowCount As Integer = 1

	' Iterate over the product list and fill the worksheet
	For Each product As Product In productList
		ws("A" & rowCount).Value = product.Id.ToString()
		ws("B" & rowCount).Value = product.ProductName
		ws("C" & rowCount).Value = product.ProductDescription
		ws("D" & rowCount).Value = product.ProductPrice
		ws("E" & rowCount).Value = product.ProductWeight
		ws("F" & rowCount).Value = product.ProductManufacturingDate
		ws("G" & rowCount).Value = product.ProductExpiryDate
		rowCount += 1
	Next product
	wb.SaveAs("product.xlsx") ' Save the workbook as an Excel file
End Sub
$vbLabelText   $csharpLabel

我們以非常簡單方便的方式將清單製作成 Excel 檔案。

DataTables.NET (How It Works For Developer):圖 5 - Excel 輸出

IronXL 提供全面的 建立 XLSX 檔案的教學讀取 Excel 的程式碼範例,以及 API說明文件,讓您以最佳方式使用其全面的 API。

在優化 ASP.NET 效能方面,我們完全仰賴 Only Core 軟體,確保精簡、有效率的開發環境。 利用 DataTables.NET 作為本機託管套件可進一步增強回應能力,將外部依賴性降至最低,以簡化資料處理和 Excel 匯出。 此外,在這個最佳化且自成一格的生態系統中,有效率地貢獻程式碼將變得無懈可擊。

IronPdf 是專門用來將網頁、URL 和 HTML 轉換成 PDF 文件的解決方案。 生成的 PDF 將保留原始網頁的格式和風格元素。 此工具對於建立 PDF 形式的網頁內容(例如報告和發票)尤其有效。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

結論

總而言之,在 ASP.NET distribution repo 專案中利用 DataTables.NET 進行伺服器端處理,證明是有效處理大量資料集的良好策略。 此方法可確保以可管理的小塊傳輸資料、減少頻寬使用量並提升使用者體驗,從而達到最佳效能。 IronXL.Excel 的整合進一步擴展了應用程式的功能,可毫不費力地將表格資料匯出至 Excel,以進行全面的資料分析和報告。

透過採用這些技術,開發人員可以建立兼顧豐富互動性與資源效率的網路應用程式,為使用者提供無縫且反應迅速的體驗,尤其是在涉及大型資料集的情況下。 IronXL 提供多種 IronXL的授權選項,視開發人員的數量、專案和再散佈需求而定。 授權是永久性的,並包含免費的支援與更新。

常見問題解答

如何將 DataTables.NET 整合到 ASP.NET 專案中?

若要將 DataTables.NET 整合到 ASP.NET 專案中,您需要建立 ASP.NET Web 應用程式、新增 DataTables Client-Side 造型套件、安裝 Entity Framework Core 套件、新增模型類別、控制器和 Razor 頁面、為伺服器端處理設定 JavaScript,然後建構並執行專案。

DataTables.NET 中的伺服器端處理是什麼?

DataTables.NET 中的伺服器端處理涉及將資料以可管理的區塊從伺服器傳送到用戶端,而非一次載入整個資料集。這可縮短載入時間,並將 CPU 和頻寬使用量降至最低,從而改善效能,尤其是在大型資料集的情況下。

為什麼 DataTables.NET 的伺服器端處理很重要?

伺服器端處理對於處理大型資料集時的效能最佳化至關重要。它允許伺服器僅傳送必要的資料到用戶端,減少瀏覽器的負載並提昇整體效率。

如何在 ASP.NET 應用程式中將表格資料匯出至 Excel?

您可以在 ASP.NET 應用程式中使用 IronXL 函式庫將表格資料匯出至 Excel。IronXL 可讓您直接從資料清單建立和操作 Excel 檔案,而不需要 Microsoft Office 或 Excel Interop。

如何在 ASP.NET 中為 DataTables 設定用戶端資料庫?

若要在 ASP.NET 中設定用戶端函式庫,請在 Visual Studio 中的解決方案上按一下滑鼠右鍵,選擇「新增」,然後選擇「用戶端函式庫」。您可以搜尋並新增所需的函式庫,例如 DataTables,這將增強您專案的功能。

設定 DataTables.NET 用於伺服器端處理的步驟為何?

若要為伺服器端處理設定 DataTables.NET,請確保您已設定 Model Class、DB Context、Controller 和 HTML table。您還需要進行 AJAX 呼叫,並在 JavaScript 檔案中設定伺服器端處理邏輯,以處理資料擷取和操作。

DataTables.NET 如何進行篩選和分頁?

DataTables.NET 中的篩選和分頁是透過伺服器端處理來管理的。伺服器會根據搜尋準則過濾資料,並透過傳送資料塊到用戶端來管理分頁,以確保資料處理的效率。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。