So sánh các bảng tính Excel bằng chương trình là một yêu cầu thường gặp khi bạn cần phát hiện thay đổi dữ liệu, kiểm tra phiên bản, hoặc tạo báo cáo. GroupDocs.Comparison Cloud SDK for .NET cung cấp một thư viện dựa trên REST mạnh mẽ, giúp dễ dàng so sánh các tệp Excel qua REST trong C#. Hướng dẫn này sẽ đưa bạn qua các bước tải lên tệp, cấu hình tùy chọn so sánh, thực hiện so sánh và lấy kết quả, với cả ví dụ mã C# và cURL.

So sánh tệp Excel qua REST trong C# trong 5 bước

  1. Tải lên tệp nguồn XLSX: Sử dụng phương thức StorageApi.UploadFile để đặt sample1.xlsx vào bộ nhớ đám mây.
using (var stream1 = new FileStream(localFilePath1, FileMode.Open, FileAccess.Read))
{
    var uploadRequest1 = new UploadFileRequest(remoteFilePath1, stream1);
    storageApi.UploadFile(uploadRequest1);
}
  1. Tải lên tệp XLSX đích: Lặp lại quá trình tải lên cho sample2.xlsx.
using (var stream2 = new FileStream(localFilePath2, FileMode.Open, FileAccess.Read))
{
    var uploadRequest2 = new UploadFileRequest(remoteFilePath2, stream2);
    storageApi.UploadFile(uploadRequest2);
}
  1. Cấu hình các tùy chọn so sánh: Tạo một đối tượng CompareOptions, đặt đường dẫn tệp nguồn và tệp đích, xác định đường dẫn đầu ra, và điều chỉnh các cài đặt như GenerateSummaryPage.
var compareOptions = new CompareOptions
{
    SourceFile = new FileInfo { FilePath = remoteFilePath1 },
    TargetFiles = new List<FileInfo>
    {
        new FileInfo { FilePath = remoteFilePath2 }
    },
    OutputPath = remoteResultPath,
    Settings = new Settings
    {
        GenerateSummaryPage = true,
        ShowDeletedContent = true,
        ShowInsertedContent = true
    }
};

Xem tài liệu API đầy đủ cho CompareOptions và Settings tại API Reference.
4. Thực hiện so sánh: Gọi CompareApi.CompareDocument với một CompareDocumentRequest.

var compareRequest = new CompareDocumentRequest(compareOptions);
var compareResult = compareApi.CompareDocument(compareRequest);
  1. Tải xuống kết quả và dọn dẹp: Lấy tệp result.xlsx đã tạo, lưu nó cục bộ và tùy chọn xóa các tệp trên máy chủ.
var downloadRequest = new DownloadFileRequest(compareResult.Path);
using (var resultStream = storageApi.DownloadFile(downloadRequest))
using (var fileStream = new FileStream(localResultPath, FileMode.Create, FileAccess.Write))
{
    resultStream.CopyTo(fileStream);
}

// Clean up
storageApi.DeleteFile(new DeleteFileRequest(remoteFilePath1));
storageApi.DeleteFile(new DeleteFileRequest(remoteFilePath2));
storageApi.DeleteFile(new DeleteFileRequest(remoteResultPath));

Ví dụ mã hoàn chỉnh: So sánh các tệp Excel qua REST trong C# bằng GroupDocs.Comparison

Ví dụ này minh họa cách tải lên hai tệp XLSX, so sánh chúng và tải xuống kết quả được đánh dấu.

using System;
using System.Collections.Generic;
using System.IO;
using GroupDocs.Comparison.Cloud.Sdk.Api;
using GroupDocs.Comparison.Cloud.Sdk.Client;
using GroupDocs.Comparison.Cloud.Sdk.Model;
using GroupDocs.Comparison.Cloud.Sdk.Model.Requests;

namespace CompareExcelFilesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configuration – replace with your actual credentials
            var config = new Configuration
            {
                ClientId = "YOUR_CLIENT_ID",
                ClientSecret = "YOUR_CLIENT_SECRET"
            };

// APIs
            var compareApi = new CompareApi(config);
            var storageApi = new StorageApi(config);

// Local and remote file names
            string localFilePath1 = "sample1.xlsx";
            string localFilePath2 = "sample2.xlsx";
            string remoteFilePath1 = "sample1.xlsx";
            string remoteFilePath2 = "sample2.xlsx";
            string remoteResultPath = "result.xlsx";
            string localResultPath = "result.xlsx";

// Upload first Excel file
            using (var stream1 = new FileStream(localFilePath1, FileMode.Open, FileAccess.Read))
            {
                var uploadRequest1 = new UploadFileRequest(remoteFilePath1, stream1);
                storageApi.UploadFile(uploadRequest1);
            }

// Upload second Excel file
            using (var stream2 = new FileStream(localFilePath2, FileMode.Open, FileAccess.Read))
            {
                var uploadRequest2 = new UploadFileRequest(remoteFilePath2, stream2);
                storageApi.UploadFile(uploadRequest2);
            }

// Prepare comparison options
            var compareOptions = new CompareOptions
            {
                SourceFile = new FileInfo { FilePath = remoteFilePath1 },
                TargetFiles = new List<FileInfo>
                {
                    new FileInfo { FilePath = remoteFilePath2 }
                },
                OutputPath = remoteResultPath,
                Settings = new Settings
                {
                    // Example: show changes in a new sheet
                    GenerateSummaryPage = true,
                    ShowDeletedContent = true,
                    ShowInsertedContent = true
                }
            };

// Execute comparison
            var compareRequest = new CompareDocumentRequest(compareOptions);
            var compareResult = compareApi.CompareDocument(compareRequest);

// Download the result file
            var downloadRequest = new DownloadFileRequest(compareResult.Path);
            using (var resultStream = storageApi.DownloadFile(downloadRequest))
            using (var fileStream = new FileStream(localResultPath, FileMode.Create, FileAccess.Write))
            {
                resultStream.CopyTo(fileStream);
            }

// Optional: clean up remote files
            storageApi.DeleteFile(new DeleteFileRequest(remoteFilePath1));
            storageApi.DeleteFile(new DeleteFileRequest(remoteFilePath2));
            storageApi.DeleteFile(new DeleteFileRequest(remoteResultPath));

Console.WriteLine("Comparison completed. Result saved to " + localResultPath);
        }
    }
}

Lưu ý: Ví dụ mã này minh họa chức năng cốt lõi. Trước khi sử dụng trong dự án của bạn, hãy chắc chắn cập nhật mọi đường dẫn tệp và giá trị cấu hình để phù hợp với môi trường thực tế của bạn, xác minh rằng tất cả các phụ thuộc cần thiết đã được cài đặt đúng cách, và kiểm tra kỹ lưỡng trong môi trường phát triển. Nếu gặp bất kỳ vấn đề nào, vui lòng tham khảo tài liệu chính thức hoặc liên hệ với đội hỗ trợ để được trợ giúp.

Calling the Comparison REST API with cURL

Dưới đây là một quy trình cURL thực hiện cùng một thao tác mà không cần viết mã C#. Thay thế các giá trị placeholder bằng thông tin xác thực và tên tệp thực tế của bạn.

  1. Lấy token truy cập
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
     -H "Content-Type: application/json" \
     -d '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET"}'
  1. Tải lên tệp XLSX nguồn
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/sample1.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" \
     --data-binary "@sample1.xlsx"
  1. Tải lên tệp XLSX đích
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/sample2.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" \
     --data-binary "@sample2.xlsx"
  1. Chạy so sánh
curl -X POST "https://api.groupdocs.cloud/v2.0/comparison/compare" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "source_file": {"file_path": "sample1.xlsx"},
           "target_files": [{"file_path": "sample2.xlsx"}],
           "output_path": "result.xlsx",
           "settings": {
               "generate_summary_page": true,
               "show_deleted_content": true,
               "show_inserted_content": true
           }
         }'
  1. Tải xuống kết quả
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/result.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o result.xlsx

Để xem danh sách đầy đủ các endpoint và tham số, hãy tham khảo tài liệu API chính thức.

Các yêu cầu trước và Cài đặt

  1. Cài đặt gói .NET qua NuGet:
dotnet add package GroupDocs.Comparison-Cloud
  1. Đảm bảo bạn có tài khoản GroupDocs Cloud hợp lệ và lấy Client Id và Client Secret từ bảng điều khiển.
  2. Yêu cầu .NET 6.0 hoặc mới hơn.

Bạn có thể tải xuống thư viện mới nhất từ trang tải xuống.

Tinh chỉnh cài đặt so sánh

Đối tượng Settings bên trong CompareOptions cho phép bạn kiểm soát đầu ra. Các điều chỉnh phổ biến bao gồm:

  • GenerateSummaryPage - thêm một trang tóm tắt với thống kê thay đổi.
  • ShowDeletedContent - làm nổi bật các ô đã bị xóa.
  • ShowInsertedContent - làm nổi bật các ô mới được thêm.

Các thuộc tính này đã được sử dụng trong ví dụ mã ở trên. Đối với các tùy chọn bổ sung như bảo vệ Password hoặc StyleChangeDetection, hãy tham khảo Tham chiếu API.

Kết luận

Việc so sánh các tệp Excel qua REST trong C# trở nên đơn giản với GroupDocs.Comparison Cloud SDK for .NET. Bằng cách làm theo các bước, bạn có thể tải lên các tệp XLSX, cấu hình các cài đặt so sánh chi tiết, thực hiện so sánh và lấy về một workbook kết quả mà rõ ràng đánh dấu các khác biệt. Hãy nhớ bảo vệ thông tin xác thực API của bạn, tuân thủ giới hạn kích thước tệp và sử dụng giấy phép tạm thời cho việc phát triển. Khi bạn đã sẵn sàng cho môi trường sản xuất, mua giấy phép đầy đủ từ trang giá để mở khóa việc sử dụng không giới hạn.

Câu hỏi thường gặp

  • Làm thế nào để so sánh các tệp Excel qua REST trong C# bằng GroupDocs.Comparison?
    Sử dụng SDK để tải lên hai tệp XLSX, thiết lập CompareOptions, gọi CompareDocument, và tải xuống tệp kết quả. Quy trình đầy đủ được minh họa trong các phần mã và cURL ở trên.

  • Phương thức xác thực nào mà REST API yêu cầu?
    API sử dụng OAuth 2.0 cùng với client‑id và client‑secret của bạn để lấy token truy cập, token này phải được gửi trong header Authorization: Bearer cho mỗi yêu cầu.

  • Tôi có thể tùy chỉnh những thay đổi nào được làm nổi bật trong kết quả so sánh không?
    Có. Điều chỉnh đối tượng Settings (ví dụ: GenerateSummaryPage, ShowDeletedContent, ShowInsertedContent) để kiểm soát cách hiển thị các khác biệt.

  • Có đủ giấy phép tạm thời để thử nghiệm không?
    Một giấy phép tạm thời từ trang giấy phép tạm thời hoạt động cho việc phát triển và thử nghiệm. Đối với triển khai sản xuất, hãy mua giấy phép đầy đủ.

Đọc thêm