.NET ヘルプ

Datatables .NET(開発者にとっての動作方法)

更新済み 1月 14, 2024
共有:

ASP.NET開発者は、ソート、検索、ページネーションなどの高度な機能を持つ表形式データやHTMLテーブルを効率的に表示する方法をよく求めます。 DataTables.NET は、インタラクティブで多機能なテーブルの作成を容易にする強力なjQuery、JavaScriptライブラリ、および非常に柔軟なツールです。 この記事では、サーバーサイド処理のためのテーブル拡張ライブラリであるDataTables.NETの配布ファイルをASP.NETプロジェクトに統合し、表形式データの表示とユーザーエクスペリエンスを向上させる方法を探ります。

ASP.NET WebアプリケーションでDataTablesを使用する方法

  1. ASP.NET ウェブアプリケーションを作成する

  2. データテーブルクライアントサイドスタイリングパッケージを追加

  3. エンティティフレームワークコアパッケージをインストールします。コアソフトウェアのみ。

  4. モデルクラス、コントローラー、およびRazorページを追加

  5. JSファイルにJavaScriptコードを追加する

  6. 設定の構成

  7. プログラムをビルドして実行する

  8. 以下を使用してデータをExcelファイルにエクスポート IronXL

Datatables.NETとは何ですか?

Datatables.NETは、CDNを作成し、.NETアプリケーション内でインタラクティブなテーブルを操作できるようにするjQuery JavaScriptライブラリです。 それは、動的および静的なHTMLテーブルに対してページネーション、ソート、フィルタリング、スクロールなどの包括的なAPI機能を提供するjQuery DataTablesプラグインに基づいています。 それは、SQLデータベース、AJAX、またはインメモリオブジェクトなどさまざまなデータソースで動作できる、テーブル強化ライブラリです。

サーバーサイドプロセッシング

APIエンドポイントが大量の製品データセットを提供するシナリオを考えてみてください。 標準的なアプローチでは、jQuery DataTablesがこのAPIにAJAXコールを行い、JSON形式で製品のリストを取得し、HTMLテーブルをレンダリングします。 これはクライアントサイド処理として知られており、通常100から1000件のレコード範囲の小規模データセットに対して効率的です。 しかし、データセットが10,000件以上に拡大した場合はどうなりますか?

多数のレコードを扱う場合、データセット全体を一度にブラウザに送信することは非現実的になります。 10,000件のレコードを一度に送信することは、帯域幅の面でも無駄が多く、ブラウザのリソースにも負担をかけます。 そのような場合、サーバーサイド処理と呼ばれる別のアプローチが、パフォーマンスを最適化するために重要になります。

サーバーサイド処理では、全体のデータセットを送信する代わりに、APIは管理しやすいチャンクでデータを送信します。通常、1ページあたり約50レコードのページネーションが行われます。 これにより、jQuery DataTablesが限られた数のレコードを読み込むため、ロード時間が大幅に改善されます。 (約50) データセット全体を一度に扱う代わりに。 このアプローチにより、CPUおよび帯域幅の使用量を削減し、APIとDataTableとの間のより効率的なインタラクションが実現します。

この記事では、大規模なデータセットを効率的に処理および表示しながら、Webアプリケーションの全体的なパフォーマンスを向上させるために、ASP.NET Razor Pageアプリケーションにおけるサーバーサイド処理の実装について探ります。

ASP.NET 8でDatatables.NETの始め方

開始するには、Datatables.NETのクライアントサイドライブラリをプロジェクトに追加する必要があります。 この記事では、ASP.NET Core Web Appを使用します。 (Razor Pages (レイザーページ)) .NET 8を使用したプロジェクト。要件に応じて任意のWeb Appプロジェクトを使用できます。

クライアントサイドライブラリを追加するには、ソリューションを右クリックして「追加」>「クライアントサイドライブラリ」を選択し、以下のようにデータテーブルを検索します。

.NETデータテーブル (開発者向けの動作方法):図1 - クライアントサイドライブラリの追加

さて、モデルクラス、DBコンテキスト、コントローラー、HTMLテーブル、およびAJAXコールを追加する必要があります。

その前に、アプリケーションをデータベースと接続するためにEntityFramework NuGetパッケージをインストールする必要があります。 この記事では、コードファーストアプローチを使用しますが、データベースファーストをお好みに応じて使用することもできます。

以下のローカルホストパッケージをインストールしてください:

  1. Microsoft.EntityFrameworkCore

  2. マイクロソフト.EntityFrameworkCore.Design

  3. Microsoft.EntityFrameworkCore.SqlServer

  4. Microsoft.EntityFrameworkCore.Tools(マイクロソフト エンティティ フレームワーク コア ツールズ)

    上記のパッケージをインストールするには、NuGet パッケージ マネージャー コンソールで install-package コマンドを使用するか、NuGet パッケージ マネージャー ソリューションから検索してインストールしてください。

モデルクラスを追加

この例では 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
VB   C#

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

高度なインタラクションコントロールを追加

wwwroot>jsフォルダの中にProductDatatables.jsを追加して、ページネーションや検索などの高度なコントロールを追加します。

//add advanced interaction controls
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "ajax": {
            "url": "/api/Product",
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0].data,
            "visible": false,
            "searchable": false
        }],
        "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 },
            {
                "render": function (data, row) { return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "'); >Delete</a>"; }
            },
        ]
    });
});
//add advanced interaction controls
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "ajax": {
            "url": "/api/Product",
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0].data,
            "visible": false,
            "searchable": false
        }],
        "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 },
            {
                "render": function (data, row) { return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "'); >Delete</a>"; }
            },
        ]
    });
});
'add advanced interaction controls
$(document).ready([function] () {
	$("#productDatatable").DataTable({
		"processing":= True, "serverSide":= True, "filter":= True, "ajax":= {
			"url":= "/api/Product",
			"type":= "POST",
			"datatype":= "json"
		},
		"columnDefs":= ({
			"targets":= (0).data,
			"visible":= False,
			"searchable":= False
		}), "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
		},
		{
			"render":= [function] (data, row) { Return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" & row.id & "'); >Delete</a>"; }
		},
		)
}); })
VB   C#

次に、HTMLテーブルを追加する必要があります。

HTMLテーブルを追加

index.cshtml ファイルに以下のコードを記述し、静的なHTMLページを追加します。

//static HTML page
@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>
}
//static HTML page
@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>
}
'static HTML page
page model ReadOnly Property () As IndexModel
	ViewData ("Title") = "Home page"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <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
"100%" cellspacing="0"> (Of thead) (Of tr) (Of th) Id</th> (Of th) Product Name</th> (Of th) Product Price</th> (Of th) Product Weight</th> (Of th) Product Description</th> (Of th) Product Manufacturing [Date]</th> (Of th) Product Expiry [Date]</th> (Of th) Actions</th> </tr> </thead> </table> </div> </div> section Scripts
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend <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
"table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Friend <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
"productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Friend <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
"width:90%; margin:0 auto;"> <table id="productDatatable" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
"container"> <br /> <div style="width:90%; margin:0 auto;"> <table id
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
"stylesheet" /> <div Class="container"> <br /> <div style
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class
"~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class
Private Private Private Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <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>
	"~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src="~/js/ProductDatatable.js"></script>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src
	"~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src
	Private Private Private <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src
End Class
VB   C#

コントローラーを追加する必要があります。

製品コントローラーを追加

エンドポイントを作成し、プルリクエストを直接受け付けるためのプロダクトコントローラを追加します。

[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.ToList();
            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 ex)
        {
            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.ToList();
            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 ex)
        {
            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.ToList()
			If Not String.IsNullOrEmpty(searchValue) Then
				productData = productData.Where(Function(m) m.ProductName.Contains(searchValue) m.ProductDescription.Contains(searchValue) 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 ex As Exception
			Throw
		End Try
	End Function
End Class
VB   C#

ここでは、サーバーサイドでページネーションと検索を実装しました。

それでは、データベースを設定し、Program.cs クラスに設定を追加する必要があります。 .NET 5またはそれ以下のバージョンを使用している場合、Startup.csクラスで実行する必要があるかもしれません。

まず、以下の接続文字列をappsettings.jsonファイルに追加してください。

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

次に、以下のコードをProgram.csクラスに追加してください。

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. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
         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. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
         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. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
		 app.UseHsts()
	 End If
	 app.UseHttpsRedirection()
	 app.UseStaticFiles()
	 app.UseRouting()
	 app.UseAuthorization()
	 app.MapControllers()
	 app.MapRazorPages()
	 app.Run()
End Sub
VB   C#

コードファーストアプローチを使用しているため、マイグレーションを実行する必要があります。

パッケージマネージャーコンソールで次のコマンドを実行してください。

Add-Migration init

上記のコマンドはマイグレーションを作成します。 これらのマイグレーションをデータベースに適用する必要があります。 パッケージマネージャーコンソールで次のコマンドを実行してください。

Update-Database

上記のコマンドは、データベースにテーブルを作成します。 製品テーブルにダミーデータを追加します。ランダムなデータを生成することもできます。 モッカルー.

では、このアプリケーションを構築して実行してください。

出力

以下の内容を日本語に翻訳してください:

非常にインタラクティブなUIと高度な操作コントロールを備えていることがわかります。

データテーブル.NET (開発者向けの動作): 図2 - 出力

以下のように、ページネーションはサーバー側で実装されています。

データテーブルズ .NET(開発者向けの使用方法): 図3 - ページネーション

出力UI

そのデータは、リッチなUIコントロールでクライアント側にレンダリングされます。

データテーブル .NET (開発者にとっての動作方法): 図4 - ユーザーインターフェース (ユーザーインターフェース (UI))

DataTables.NETのドキュメントについて詳しく知りたい場合は、こちらをクリックしてください。 これ.

IronXL の紹介

IronXL は、.NETアプリケーションでExcelファイルを操作できるライブラリです。 できる 作成, 読込, 編集、および 保存 XLS、XLSX、CSV、TSVなど、さまざまな形式のExcelドキュメント。Microsoft OfficeやExcel Interopのインストールは不要です。 .NET 8、7、6、5、Core、Framework、Azureをサポートしています。

データをExcelやCSVファイルにエクスポートする必要があることがよくあります。 この場合、IronXLは最適な選択です。 さて、データをExcelファイルにエクスポートするコードを書きます。

IronXLをインストール

パッケージ マネージャー コンソールに次のコマンドを入力して、プロジェクトに IronXL ライブラリをインストールします。

Install-Package ironXL.Excel

これは、IronXLと必要な依存関係をプロジェクトにインストールします。

エクスポートデータをExcelに出力

製品リストをExcelファイルに変換するコードを書きましょう。

public void ExportToExcel(List<Product> productList)
   {
       WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
       WorkSheet ws = wb.DefaultWorkSheet;
       int rowCount = 1;
       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");
   }
public void ExportToExcel(List<Product> productList)
   {
       WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
       WorkSheet ws = wb.DefaultWorkSheet;
       int rowCount = 1;
       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");
   }
Public Sub ExportToExcel(ByVal productList As List(Of Product))
	   Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	   Dim ws As WorkSheet = wb.DefaultWorkSheet
	   Dim rowCount As Integer = 1
	   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")
End Sub
VB   C#

リストから非常にシンプルかつ簡単な方法でExcelファイルを作成しました。

Datatables .NET(開発者向けの仕組み):図5 - Excel出力

IronXLは、包括的な チュートリアル, コード例、および ドキュメント その包括的なAPIを最良の方法で使用するため。

ASP.NETのパフォーマンスを最適化する際には、Only Core Software にのみ依存し、スリムで効率的な開発環境を確保しています。 DataTables.NETをローカルホストされたパッケージとして利用することで、応答性がさらに向上し、外部依存関係が最小限に抑えられ、データ処理とExcelエクスポートの効率が向上します。 さらに、この最適化され自己完結型のエコシステム内で効率的にコードを貢献することがスムーズになります。

結論

要約すると、ASP.NET配布リポジトリプロジェクトにおいてサーバーサイド処理のためにDataTables.NETを活用することは、大規模なデータセットを効率的に処理するための良い戦略であることを証明しています。 このアプローチは、データを適切なサイズのチャンクに分割して送信することで、帯域幅の使用を軽減し、ユーザー体験を向上させながら最適化されたパフォーマンスを保証します。 IronXLの統合により、アプリケーションの機能がさらに拡張され、簡単に表形式のデータをExcelにエクスポートして、包括的なデータ分析とレポート作成が可能になります。

これらの技術を採用することにより、開発者はリッチなインタラクティビティとリソース効率のバランスを取ったウェブアプリケーションを作成することができ、特に大規模なデータセットが関係するシナリオで、ユーザーにシームレスかつレスポンシブな体験を提供できます。 IronXLはさまざまな ライセンス開発者の数、プロジェクトの数、および再配布のニーズに応じて。 ライセンスは永久的であり、無料のサポートおよびアップデートが含まれています。

< 以前
Sqlite C# .NET(開発者向けの動作方法)
次へ >
C# Null合体演算子(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >