Excel 워크시트를 프로그래밍 방식으로 비교하는 것은 데이터 변경을 감지하거나, 수정 내역을 감사하거나, 보고서를 생성해야 할 때 자주 요구되는 작업입니다. GroupDocs.Comparison Cloud SDK for .NET은 REST 기반 라이브러리를 제공하여 C#에서 REST를 통해 Excel 파일을 쉽게 비교할 수 있게 해줍니다. 이 가이드는 파일 업로드, 비교 옵션 구성, 비교 실행 및 결과 검색 과정을 C# 코드와 cURL 예제와 함께 단계별로 안내합니다.
REST를 사용한 C#에서 Excel 파일 비교 5단계
- 소스 XLSX 파일 업로드:
StorageApi.UploadFile메서드를 사용하여sample1.xlsx를 클라우드 스토리지에 배치합니다.
using (var stream1 = new FileStream(localFilePath1, FileMode.Open, FileAccess.Read))
{
var uploadRequest1 = new UploadFileRequest(remoteFilePath1, stream1);
storageApi.UploadFile(uploadRequest1);
}
- 대상 XLSX 파일 업로드:
sample2.xlsx에 대해 업로드를 반복합니다.
using (var stream2 = new FileStream(localFilePath2, FileMode.Open, FileAccess.Read))
{
var uploadRequest2 = new UploadFileRequest(remoteFilePath2, stream2);
storageApi.UploadFile(uploadRequest2);
}
- 비교 옵션 구성:
CompareOptions객체를 생성하고, 소스 및 대상 파일 경로를 설정하고, 출력 경로를 정의하며,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
}
};
CompareOptions 및 Settings에 대한 전체 API 참조는 API Reference에서 확인하십시오.
4. 비교 실행: CompareDocumentRequest를 사용하여 CompareApi.CompareDocument를 호출합니다.
var compareRequest = new CompareDocumentRequest(compareOptions);
var compareResult = compareApi.CompareDocument(compareRequest);
- 결과 다운로드 및 정리: 생성된
result.xlsx를 가져와 로컬에 저장하고, 필요에 따라 원격 파일을 삭제합니다.
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));
전체 코드 예제: C#에서 REST를 사용하여 Excel 파일 비교 (GroupDocs.Comparison 사용)
이 예제에서는 두 개의 XLSX 파일을 업로드하고, 비교하며, 강조 표시된 결과를 다운로드하는 방법을 보여줍니다.
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);
}
}
}
참고: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에서 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서 또는 지원 팀에 문의하십시오.
cURL을 사용하여 Comparison REST API 호출하기
아래는 C# 코드를 작성하지 않고 동일한 작업을 수행하는 cURL 워크플로우입니다. 자리 표시자 값을 실제 자격 증명 및 파일 이름으로 교체하십시오.
- 액세스 토큰 얻기
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"}'
- 소스 XLSX 파일 업로드
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"
- 대상 XLSX 파일 업로드
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"
- 비교 실행
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
}
}'
- 결과 다운로드
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/result.xlsx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o result.xlsx
엔드포인트 및 매개변수의 전체 목록은 공식 API 문서를 참조하십시오.
사전 요구 사항 및 설정
- NuGet을 통해 .NET 패키지를 설치합니다:
dotnet add package GroupDocs.Comparison-Cloud
- 유효한 GroupDocs Cloud 계정이 있는지 확인하고 대시보드에서 Client Id와 Client Secret을 가져옵니다.
- .NET 6.0 이상이 필요합니다.
최신 라이브러리는 다운로드 페이지에서 다운로드할 수 있습니다.
비교 설정 미세 조정
Settings 객체는 CompareOptions 내부에 있으며 출력 제어를 가능하게 합니다. 일반적인 조정 항목은 다음과 같습니다:
- GenerateSummaryPage - 변경 통계가 포함된 요약 시트를 추가합니다.
- ShowDeletedContent - 삭제된 셀을 강조 표시합니다.
- ShowInsertedContent - 새로 추가된 셀을 강조 표시합니다.
위 코드 예제에서 이미 이러한 속성이 사용되었습니다. Password 보호 또는 StyleChangeDetection와 같은 추가 옵션에 대해서는 API Reference를 참조하십시오.
결론
C#에서 REST를 통해 Excel 파일을 비교하는 것이 GroupDocs.Comparison Cloud SDK for .NET을 사용하면 간단해집니다. 단계별로 진행하면 XLSX 파일을 업로드하고, 상세 비교 설정을 구성하며, 비교를 실행하고, 차이점을 명확히 표시한 결과 워크북을 가져올 수 있습니다. API 자격 증명을 안전하게 보관하고, 파일 크기 제한을 준수하며, 개발 단계에서는 임시 라이선스를 사용하십시오. 프로덕션 준비가 되면 가격 페이지에서 전체 라이선스를 구매하여 무제한 사용을 활성화하세요.
자주 묻는 질문
C#와 GroupDocs.Comparison을 사용하여 REST를 통해 Excel 파일을 비교하려면 어떻게 해야 하나요?
SDK를 사용하여 두 개의 XLSX 파일을 업로드하고,CompareOptions를 설정한 뒤CompareDocument를 호출하여 결과 파일을 다운로드합니다. 전체 워크플로는 위의 코드 및 cURL 섹션에 설명되어 있습니다.REST API가 요구하는 인증 방법은 무엇입니까?
API는 클라이언트‑id와 클라이언트‑secret을 사용하여 OAuth 2.0으로 액세스 토큰을 얻으며, 이 토큰은 모든 요청에 대해Authorization: Bearer헤더에 포함되어 전송되어야 합니다.비교 결과에서 강조 표시되는 변경 사항을 사용자 정의할 수 있나요?
예.Settings객체(예:GenerateSummaryPage,ShowDeletedContent,ShowInsertedContent)를 조정하여 차이점의 표시 방식을 제어할 수 있습니다.임시 라이선스로 테스트에 충분한가요?
임시 라이선스는 임시 라이선스 페이지에서 얻을 수 있으며 개발 및 테스트에 사용할 수 있습니다. 프로덕션 배포를 위해서는 정식 라이선스를 획득하십시오.
