Cách chuyển đổi dữ liệu JSON sang Excel trong C#

Ban đầu, khi tôi bắt đầu thực hiện yêu cầu này, mọi người đề xuất sử dụng bất kỳ thư viện phụ trợ nào để đọc và chuyển đổi dữ liệu excel thành các đối tượng JSON. Nhưng rất khó để gửi yêu cầu đến máy chủ mọi lúc. Mặt khác, thật dễ dàng để chuyển đổi tệp excel trên máy khách thành đối tượng JSON bằng cách sử dụng JavaScript thuần túy

Có một plugin JavaScript XSLX có thể được sử dụng để đọc các tệp excel dưới dạng chuỗi nhị phân và chuyển đổi chúng thành các đối tượng JSON

Yêu cầu plugin. xlsx. đầy. tối thiểu. js

Cài đặt

Bao gồm liên kết CDN trong thẻ head của tệp HTML như thế này

Cách chuyển đổi dữ liệu JSON sang Excel trong C#

private void GetExcel_Click(object sender, EventArgs e)  
        {  
            GenerateFromJSON(apiurl);  
        }  
 string apiurl = "https://www.grapecity.com/componentone/demos/aspnet/5/C1WebAPI/latest/api/excel";  //web api demo url  
 
 public void GenerateFromJSON(string webapiurl)  
        {  
            var url = "http://services.odata.org/V4/Northwind/Northwind.svc/Products?$format=json";  //get products from ODATA service  
 
            using (var clientjs = new HttpClient())  
            {  
                HttpResponseMessage responseJSON = clientjs.GetAsync(url).Result;    
                responseJSON.EnsureSuccessStatusCode();  
                var responseBody = responseJSON.Content.ReadAsStringAsync().Result;  //Get JSON from ODATA service  
 
                var data = JsonConvert.DeserializeObject(responseBody)["value"];  //use JsonConvert to deserialize raw json  
 
                using (var client = new HttpClient())  
                using (var formData = new MultipartFormDataContent())  
                {  
                    var fileFormat = "xlsx";  
                    formData.Add(new StringContent("Test"), "FileName");  
                    formData.Add(new StringContent(fileFormat), "FileFormat");  
                    formData.Add(new StringContent(JsonConvert.SerializeObject(data)), "Data");   
                   //Call WebAPI to get Excel  
                    var response = client.PostAsync(webapiurl, formData).Result;  
                    if (!response.IsSuccessStatusCode)  
                    {  
                        MessageBox.Show("Invalid response.");  
                        return;  
                    }  
                    var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());  
                    if (!Directory.Exists(tempPath))  
                    {  
                        Directory.CreateDirectory(tempPath);  
                    }  
                    //Save Excel to Tem directory.  
                    var tempFilePath = Path.Combine(tempPath, string.Format("{0}.{1}", "Test", fileFormat));  
                    using (var newFile = File.Create(tempFilePath))  
                    {  
                        response.Content.ReadAsStreamAsync().Result.CopyTo(newFile);  
                    }  
                    //Open Excel to view.  
                    Process.Start(tempFilePath);  
                }  
            }  
        }

Tệp Excel kết quả

Cách chuyển đổi dữ liệu JSON sang Excel trong C#

Bây giờ chúng ta sẽ xem xét việc tạo tệp Excel từ ADO. NET DataTable. Chúng tôi sẽ sử dụng DataTable. WriteXml để lấy XML, sau đó gửi XML tới API Web để tạo Excel. Không cần thiết phải sử dụng DataTable XML, Nội dung của tệp dữ liệu xml phải giống như bộ sưu tập, một phần tử gốc có nhiều phần tử giống như các phần tử con của nó


    
        1000
    
    ......
 

Bảng dữ liệu XML

Cách chuyển đổi dữ liệu JSON sang Excel trong C#

private void GenerateExcel_Click(object sender, EventArgs e)  
       {  
           GenerateFromXML(apiurl);  
       }  
 string apiurl = "https://www.grapecity.com/componentone/demos/aspnet/5/C1WebAPI/latest/api/excel";  //web api demo url  
 
 public void GenerateFromXML(string webapiURL)  
        {  
 
            DataTable dt = new System.Data.DataTable();  
            dt.TableName = "Products";  
            dt.Columns.Add("ID", typeof(int));  
            dt.Columns.Add("Product", typeof(string));  
            dt.Columns.Add("Active", typeof(bool));  
            dt.Rows.Add(1, "Electronics", true);  
            dt.Rows.Add(2, "Food", true);  
            dt.Rows.Add(3, "Garments", true);  
            dt.Rows.Add(4, "Stationary", true);  
            dt.Rows.Add(5, "Antiques", false);  
 
           //Create Temp directory to save xml file  
            var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());  
             Directory.CreateDirectory(tempDir);  
            string path = Path.Combine(tempDir, string.Format("{0}.{1}", "Prodcuts", "xml"));  
           //Write to xml file  
            dt.WriteXml(path, System.Data.XmlWriteMode.IgnoreSchema);  
 
            //Create HttpClient and MultipartFormDataContent  
            using (var client = new HttpClient())  
            using (var formData = new MultipartFormDataContent())  
            using (var fromFile=File.OpenRead(path))  
            {  
 
                formData.Add(new StringContent("Test"), "FileName");  
                formData.Add(new StringContent("xlsx"), "FileFormat");  
                formData.Add(new StreamContent(fromFile), "DataFile",Path.GetFileName(path));  
                //Call WebAPI  
                var response = client.PostAsync(webapiURL, formData).Result;  
                if (!response.IsSuccessStatusCode)  
                {  
                    MessageBox.Show("Invalid response.");  
                    return;  
                }  
                var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());  
                if (!Directory.Exists(tempPath))  
                {  
                    Directory.CreateDirectory(tempPath);  
                }  
                //Save Excel file to Temp directory  
                var tempFilePath = Path.Combine(tempPath, string.Format("{0}.{1}", "Test", fileFormat));  
                using (var newFile = File.Create(tempFilePath))  
                {  
                    response.Content.ReadAsStreamAsync().Result.CopyTo(newFile);  
                }  
                //Open In Excel  
                Process.Start(tempFilePath);  
            }  
        }

Kết quả Excel từ XML

Cách chuyển đổi dữ liệu JSON sang Excel trong C#

Bạn có thể tìm thấy nhiều mẫu hơn trong thư mục "~\Documents\ComponentOne Samples\Web Api" khi cài đặt phiên bản Web API hoặc DataServices

API Web khả dụng với các phiên bản DataServices, WinForms DataServices và Enterprise. DataService Edition cung cấp các khả năng dưới đây giúp phát triển ứng dụng dễ dàng

Làm cách nào để xuất dữ liệu từ JSON sang Excel trong C#?

Các bước chuyển đổi tệp JSON sang Excel bằng C# .
Thêm tham chiếu đến Aspose. Thư viện ô từ Trình quản lý gói NuGet để chuyển đổi tệp JSON sang Excel
Tạo kiểu cho tiêu đề dữ liệu JSON bằng cách đặt các thuộc tính khác nhau như căn chỉnh, màu phông chữ và cờ Đậm

Làm cách nào để phân tích cú pháp dữ liệu JSON trong Excel?

Phân tích cú pháp văn bản dưới dạng JSON hoặc XML (Power Query) .
Chọn cột Nhân viên bán hàng
Chọn Biến đổi > Phân tích cú pháp > JSON
Chọn Ghi để xem các giá trị
Chọn Mở rộng. biểu tượng bên cạnh tiêu đề cột Nhân viên bán hàng. Từ hộp thoại Mở rộng cột, chỉ chọn các trường Tên và Họ

Làm cách nào để chuyển đổi JSON sang XLSX?

Giả sử ứng dụng .
Truy cập trang web ứng dụng Aspose
Nhấp vào “Kéo hoặc tải tệp của bạn lên”
Chọn tệp JSON bạn muốn chuyển đổi thành tệp MS Excel
Trong tùy chọn lưu dưới dạng, đảm bảo bạn đã chọn tùy chọn “XLSX”
Chọn Chuyển đổi thành một trang tính hoặc Chuyển đổi thành nhiều trang tính dựa trên nhu cầu của bạn

Làm cách nào để chuyển đổi tệp JSON thành CSV?

Chuyển đổi JSON sang CSV - Đây là cách. .
1 Tải lên tệp JSON của bạn. Duyệt qua máy tính của bạn để tìm tài liệu JSON mà bạn muốn chuyển đổi thành tệp CSV. .
2 Chuyển đổi tệp JSON sang tệp CSV. Sau khi tải lên, tệp JSON của bạn sẽ tự động bắt đầu chuyển đổi dữ liệu của bạn sang định dạng mới. .
3 Lưu tệp của bạn hoặc gửi đến email của bạn