Xuất bảng html sang csv góc

scope="col"># ... *ngFor="let user of users"> scope="row">{{ user.id }} ...

Xin chào rani,

Kiểm tra ví dụ này. Bây giờ hãy tham khảo và sửa mã của bạn

cơ sở dữ liệu

Đối với ví dụ này, tôi đã sử dụng cơ sở dữ liệu Northwind mà bạn có thể tải xuống bằng liên kết được cung cấp bên dưới

Tải xuống cơ sở dữ liệu Northwind

HTML


    
    
    


    
    

Id Name City Country {{employee.Id}} {{employee.Name}} {{employee.City}} {{employee.Country}}

không gian tên

C#

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

VB. Mạng lưới

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Services

Mã số

C#

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function

Ảnh chụp màn hình

Xuất bảng html sang csv góc

Trong khi làm việc trên một ứng dụng web, có nhiều trường hợp chúng tôi cho phép người dùng tải dữ liệu xuống các định dạng cụ thể của họ. Một yêu cầu như vậy là cho phép họ xuất dữ liệu dưới dạng bảng tính (excel) hoặc tệp CSV

Đây là một trường hợp sử dụng rất phổ biến và do đó tôi nghĩ sẽ tạo một hướng dẫn từng bước để thực hiện việc này một cách dễ dàng. Chúng tôi sẽ thảo luận về xuất khẩu thành 2 lĩnh vực chính

  • Xuất sang Excel
  • Xuất sang CSV

📝 LƯU Ý
Tôi đã tạo một kho lưu trữ trên GitHub khi triển khai này

idris-rampurawala / ng-data-export

Minh họa dịch vụ export xuất dữ liệu ra excel, csv trong Angular 10


Xuất sang Excel

Khả năng xuất dữ liệu sang excel không chỉ mang lại một tính năng mạnh mẽ cho người dùng mà còn có khả năng tạo ra một loạt các tính năng liên quan khác để giúp người dùng của chúng tôi hiểu rõ hơn về dữ liệu. Vậy chúng ta bắt đầu như thế nào?

cài đặt phụ thuộc

# installing xlsx package
$ npm install xlsx
# installing file-saver - a solution to saving files on the client-side
$ npm install file-saver

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Tạo dịch vụ xuất khẩu

Một cách để tạo các chức năng phổ biến trong Angular là tạo một dịch vụ cho nó. Do đó, chúng tôi tạo một dịch vụ xuất sẽ có chức năng xuất tất cả các loại thông tin (excel và CSV cho bài đăng này)

Sử dụng xlsx

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 cung cấp một bộ tiện ích rất phong phú để tạo hoặc phân tích bảng tính. Để đơn giản, chúng tôi sẽ tập trung vào một vài tiện ích ở đây

1️⃣ Xuất bảng HTML

Nếu chúng ta muốn xuất một

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
6 sang excel, thì khá dễ dàng vì
[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 cung cấp tiện ích cho nó. Cân nhắc xem chúng ta có bàn không 👇


 class="table table-sm" #userTable> 
   class="thead-dark">
    

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Bây giờ, chúng ta chỉ cần tạo một hàm


 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

0 để lấy

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

1 này và tạo excel từ nó (sử dụng

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

2 và

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

3)

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
0

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Và trong


 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

4, chúng tôi chỉ cần tạo một trình xử lý cho

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

5 để cố gắng lưu tệp dưới dạng excel trên máy khách

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
3

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Đó là khá dễ dàng, phải không?

2️⃣ Xuất dữ liệu phức tạp hơn

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 cung cấp nhiều tiện ích khác để tùy chỉnh dữ liệu trong excel (dùng tên cột excel xác định

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

7). Ví dụ: tôi đã tạo một chức năng để xuất toàn bộ dữ liệu bảng điều khiển sang excel trong một trong các dự án của mình. Hãy tạo một hàm trong

 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

0 cho cùng

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
6

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Và trong


 class="table table-sm" #userTable> 
   class="thead-dark">
    
       scope="col">#
      ...
    
  
  
     *ngFor="let user of users">
       scope="row">{{ user.id }}
      ...
    
    
  

4, chúng tôi tạo dữ liệu ở định dạng bắt buộc của
[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 để chuyển đến chức năng dịch vụ này

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
8

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Giải trình

Bối rối?

  • [WebMethod]
    public static string GetEmployees()
    {
        List employees = new List();
        string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new
                        {
                            Id = sdr["EmployeeID"],
                            Name = sdr["FirstName"] + " " + sdr["LastName"],
                            City = sdr["City"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(employees));
        }
    }
    

    VB.Net

    Public Shared Function GetEmployees() As String
        Dim employees As List(Of Object) = New List(Of Object)()
        Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As SqlCommand = New SqlCommand(sql)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        employees.Add(New With { _
                        .Id = sdr("EmployeeID"),
                        .Name = sdr("FirstName") & " " & sdr("LastName"),
                        .City = sdr("City"),
                        .Country = sdr("Country")
                    })
                    End While
                End Using
                conn.Close()
            End Using
    
            Return (New JavaScriptSerializer().Serialize(employees))
        End Using
    End Function
    5 (hoặc bảng tính) có một
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    02 (đó là một tệp thực tế) và trong đó, chúng tôi có thể thêm nhiều
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    03
  • [WebMethod]
    public static string GetEmployees()
    {
        List employees = new List();
        string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new
                        {
                            Id = sdr["EmployeeID"],
                            Name = sdr["FirstName"] + " " + sdr["LastName"],
                            City = sdr["City"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(employees));
        }
    }
    

    VB.Net

    Public Shared Function GetEmployees() As String
        Dim employees As List(Of Object) = New List(Of Object)()
        Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As SqlCommand = New SqlCommand(sql)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        employees.Add(New With { _
                        .Id = sdr("EmployeeID"),
                        .Name = sdr("FirstName") & " " & sdr("LastName"),
                        .City = sdr("City"),
                        .Country = sdr("Country")
                    })
                    End While
                End Using
                conn.Close()
            End Using
    
            Return (New JavaScriptSerializer().Serialize(employees))
        End Using
    End Function
    5 cung cấp hàm tiện ích
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    05 để chuyển đổi một mảng đối tượng thành dữ liệu excel với các tùy chọn xlsx bổ sung. Do đó, chúng tôi chỉ tạo một trình bao bọc xung quanh
    
     class="table table-sm" #userTable> 
       class="thead-dark">
        
           scope="col">#
          ...
        
      
      
         *ngFor="let user of users">
           scope="row">{{ user.id }}
          ...
        
        
      
    
    
    0 của chúng tôi để chúng tôi có thể chuyển nhiều đối tượng với các tùy chọn xlsx khác nhau. Bằng cách này, dịch vụ xuất của chúng tôi xử lý sự phức tạp và chúng tôi chỉ được yêu cầu tạo một mảng các đối tượng để chuyển đến nó
  • [WebMethod]
    public static string GetEmployees()
    {
        List employees = new List();
        string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new
                        {
                            Id = sdr["EmployeeID"],
                            Name = sdr["FirstName"] + " " + sdr["LastName"],
                            City = sdr["City"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(employees));
        }
    }
    

    VB.Net

    Public Shared Function GetEmployees() As String
        Dim employees As List(Of Object) = New List(Of Object)()
        Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As SqlCommand = New SqlCommand(sql)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        employees.Add(New With { _
                        .Id = sdr("EmployeeID"),
                        .Name = sdr("FirstName") & " " & sdr("LastName"),
                        .City = sdr("City"),
                        .Country = sdr("Country")
                    })
                    End While
                End Using
                conn.Close()
            End Using
    
            Return (New JavaScriptSerializer().Serialize(employees))
        End Using
    End Function
    5 mong đợi mảng các đối tượng ở dạng
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    08 và do đó
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    09 có nghĩa là chúng tôi muốn đặt
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    30 này vào ô (cột)
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    31 của excel
  • using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    32 là bỏ qua tiêu đề được tạo tự động từ các đối tượng được chuyển đến hàm
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    05
  • using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    34 là nối thêm dữ liệu vào cuối trang tính bắt đầu từ cột đầu tiên
  • Ngoài ra,
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    35 là một giao diện tùy chỉnh (mà tôi đã tạo) để xác định loại dữ liệu mà chức năng dịch vụ mong đợi. Nó đại diện cho một dữ liệu đối tượng hợp lệ cho
    [WebMethod]
    public static string GetEmployees()
    {
        List employees = new List();
        string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new
                        {
                            Id = sdr["EmployeeID"],
                            Name = sdr["FirstName"] + " " + sdr["LastName"],
                            City = sdr["City"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(employees));
        }
    }
    

    VB.Net

    Public Shared Function GetEmployees() As String
        Dim employees As List(Of Object) = New List(Of Object)()
        Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As SqlCommand = New SqlCommand(sql)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        employees.Add(New With { _
                        .Id = sdr("EmployeeID"),
                        .Name = sdr("FirstName") & " " & sdr("LastName"),
                        .City = sdr("City"),
                        .Country = sdr("Country")
                    })
                    End While
                End Using
                conn.Close()
            End Using
    
            Return (New JavaScriptSerializer().Serialize(employees))
        End Using
    End Function
    5

Để biết thêm thông tin, vui lòng đọc tài liệu xlsx và triển khai mẫu trên github

Làm cách nào để tạo kiểu excel?

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 không cung cấp kiểu dáng trong phiên bản mã nguồn mở của nó. Bạn có thể chọn
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
38 để được tạo kiểu và hỗ trợ tận tình

Ngoài ra, xlsx-style là một nhánh của

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 cung cấp kiểu dáng cho nó

Thêm một giải pháp thay thế rất phổ biến cho

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5 là ExcelJS. Nó cũng có kiểu dáng đi kèm nhưng cung cấp ít tiện ích hơn so với
[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
5


Xuất sang CSV

Bây giờ hãy chuyển sang phần thứ hai của quá trình xuất i. e. CSV

Đừng lo lắng 😟 nó khá dễ dàng. Chúng ta chỉ cần thêm một hàm vào

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
62 của mình, hàm này chấp nhận một mảng đối tượng cùng với tiêu đề cột để tạo CSV cho nó

[WebMethod]
public static string GetEmployees()
{
    List employees = new List();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function
3

Vào chế độ toàn màn hình Thoát chế độ toàn màn hình

Mã này khá dễ hiểu 🤓 nơi chúng tôi kiểm tra xem có bất kỳ dữ liệu nào của cột có trong dữ liệu được chuyển hay không và tạo CSV từ đó. Chúng tôi luôn có thể thay đổi dấu phân cách từ

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
63 thành bất kỳ dấu phân cách nào khác dựa trên yêu cầu của chúng tôi. cần có gói trình tiết kiệm tệp để lưu tệp trên máy của khách hàng


Chà, điều đó khá đơn giản phải không?

Nếu bạn thấy điều này hữu ích hoặc có bất kỳ đề xuất nào, vui lòng bình luận. Ngoài ra, đừng quên nhấn ❤️ hoặc 🦄 nếu bạn thích bài viết của tôi