C#에서 Excel 파일을 읽는 방법

How to Read Excel Files in C# Without Interop: Complete Developer Guide

This article was translated from English: Does it need improvement?
Translated
View the article in English

Microsoft Office 설치 없이도 스프레드시트 데이터를 읽고, 유효성을 검사하고, 내보낼 수 있는 강력한 .NET 라이브러리인 IronXL을 사용하여 C#에서 Excel 파일을 능숙하게 조작하는 방법을 알아보세요. 이 종합 튜토리얼은 데이터 유효성 검사, 데이터베이스 변환 및 REST API 통합을 포함한 실용적인 Excel 작업 방법을 보여줍니다.

빠른 시작: IronXL을 사용하여 한 줄로 셀 읽기

IronXL을 사용하면 단 한 줄의 코드로 Excel 통합 문서를 불러와 셀 값을 가져올 수 있습니다. 이 시스템은 사용 편의성을 고려하여 설계되었습니다. 상호 운용성도 없고 복잡한 설정도 필요 없으며, 데이터에 빠르게 액세스할 수 있습니다.

  1. NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/IronXL.Excel 설치하기

    PM > Install-Package IronXL.Excel
  2. 다음 코드 조각을 복사하여 실행하세요.

    var value = IronXl.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue;
  3. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    무료 체험판으로 오늘 프로젝트에서 IronXL 사용 시작하기

    arrow pointer

C#에서 IronXL을 사용하여 Excel 파일을 읽도록 설정하는 방법은 무엇인가요?

C# 프로젝트에서 Excel 파일을 읽도록 IronXL을 설정하는 데는 몇 분밖에 걸리지 않습니다. 이 라이브러리는 .XLS.XLSX 형식을 모두 지원하므로 모든 Excel 관련 작업에 다용도로 사용할 수 있습니다.

시작하려면 다음 단계를 따르세요.

  1. 엑셀 파일을 읽기 위한 C# 라이브러리를 다운로드하세요 .
  2. WorkBook.Load()를 사용하여 Excel 통합 문서를 로드하고 읽습니다.
  3. GetWorkSheet() 방법을 사용하여 워크시트에 액세스합니다.
  4. sheet["A1"].Value와 같은 직관적인 구문을 사용하여 셀 값을 읽습니다.
  5. 스프레드시트 데이터를 프로그램 방식으로 검증하고 처리합니다.
  6. Entity Framework를 사용하여 데이터를 데이터베이스로 내보내기

IronXL은 C#을 사용하여 Microsoft Excel 문서를 읽고 편집하는 데 탁월합니다. 이 라이브러리는 독립적으로 작동하며, Microsoft Excel이나 Interop이 필요하지 않습니다. 실제로 IronXL은 Microsoft.Office.Interop.Excel보다 더 빠르고 직관적인 API를 제공합니다 .

IronXL 구성품:

  • 당사 .NET 엔지니어의 전담 제품 지원
  • Microsoft Visual Studio를 통한 간편한 설치
  • 개발을 위한 무료 평가판 테스트. liteLicense의 라이선스

IronXL 소프트웨어 라이브러리를 사용하면 C# 및 VB.NET에서 Excel 파일을 읽고 생성하는 것이 간편해집니다.

IronXL을 사용하여 .XLS 및 .XLSX Excel 파일 읽기

IronXL을 사용하여 Excel 파일을 읽는 데 필요한 핵심 워크플로는 다음과 같습니다.

  1. NuGet 패키지를 통해 IronXL Excel 라이브러리를 설치하거나 .NET Excel DLL 을 다운로드하십시오.
  2. WorkBook.Load() 메서드를 사용하여 모든 XLS, XLSX 또는 CSV 문서를 읽을 수 있습니다.
  3. 직관적인 구문을 사용하여 셀 값에 액세스합니다: sheet["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;

// Load Excel workbook from file path
WorkBook workBook = WorkBook.Load("test.xlsx");

// Access the first worksheet using LINQ
WorkSheet workSheet = workBook.WorkSheets.First();

// Read integer value from cell A2
int cellValue = workSheet["A2"].IntValue;
Console.WriteLine($"Cell A2 value: {cellValue}");

// Iterate through a range of cells
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Advanced Operations with LINQ
// Calculate sum using built_in Sum() method
decimal sum = workSheet["A2:A10"].Sum();

// Find maximum value using LINQ
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);

// Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}");
Console.WriteLine($"Maximum value: {max}");
$vbLabelText   $csharpLabel

이 코드는 IronXL의 주요 기능 몇 가지를 보여줍니다. 워크북 불러오기, 주소를 이용한 셀 접근, 범위 순회, 그리고 계산 수행 등이 포함됩니다. WorkBook.Load() 메서드는 파일 형식을 지능적으로 감지하는 반면, 범위 구문 ["A2:A10"]은 Excel과 유사한 셀 선택 기능을 제공합니다. LINQ 통합을 통해 셀 컬렉션에 대한 강력한 데이터 쿼리 및 집계가 가능합니다.

이 튜토리얼의 코드 예제는 서로 다른 데이터 시나리오를 보여주는 세 가지 샘플 Excel 스프레드시트를 사용합니다.

Visual Studio 솔루션 탐색기에 표시된 세 개의 Excel 스프레드시트 파일 본 튜토리얼에서는 IronXL의 다양한 작업 방법을 설명하기 위해 샘플 Excel 파일(GDP.xlsx, People.xlsx, PopulationByState.xlsx)을 사용합니다.


IronXL C# 라이브러리는 어떻게 설치할 수 있나요?


IronXl.Excel 라이브러리를 설치하면 .NET Framework 프로젝트에 포괄적인 Excel 기능을 추가할 수 있습니다. NuGet 설치 또는 수동 DLL 통합 중에서 선택하십시오.

IronXL NuGet Install-Package

  1. Visual Studio에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 "NuGet 패키지 관리"를 선택합니다.
  2. 찾아보기 탭에서 "IronXl.Excel"을 검색하세요.
  3. 설치 버튼을 클릭하여 IronXL을 프로젝트에 추가하세요.

 IronXL .Excel Install-Package를 보여주는 NuGet 패키지 관리자 인터페이스 Visual Studio의 NuGet 패키지 관리자를 통해 IronXL을 설치하면 종속성 관리가 자동으로 이루어집니다.

또는 패키지 관리자 콘솔을 사용하여 IronXL을 설치하십시오.

  1. 패키지 관리자 콘솔을 엽니다(도구 → NuGet 패키지 관리자 → 패키지 관리자 콘솔).
  2. 설치 명령을 실행하세요:
Install-Package IronXL.Excel

NuGet 웹사이트에서도 패키지 세부 정보를 확인할 수 있습니다.

수동 설치

수동 설치의 경우, IronXL .NET Excel DLL을 다운로드하고 Visual Studio 프로젝트에서 직접 참조하십시오.

엑셀 통합 문서를 불러오고 읽는 방법은 무엇인가요?

WorkBook 클래스는 전체 Excel 파일을 나타냅니다. XLS, XLSX, CSV 및 TSV 형식의 파일 경로를 허용하는 WorkBook.Load() 메서드를 사용하여 Excel 파일을 로드합니다.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
using IronXL;
using System;
using System.Linq;

// Load Excel file from specified path
WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");

Console.WriteLine("Workbook loaded successfully.");

// Access specific worksheet by name
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");

// Read and display cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");

// Perform additional operations
// Count non_empty cells in column A
int rowCount = sheet["A:A"].Count(cell => !cell.IsEmpty);
Console.WriteLine($"Column A has {rowCount} non_empty cells");
$vbLabelText   $csharpLabel

WorkBook에는 개별 Excel 시트를 나타내는 여러 개의 WorkSheet 객체가 포함되어 있습니다. GetWorkSheet() 사용하여 이름으로 워크시트에 액세스하세요.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs
using IronXL;
using System;

// Get worksheet by name
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");

Console.WriteLine("Worksheet 'GDPByCountry' not found");
// List available worksheets
foreach (var sheet in workBook.WorkSheets)
{
    Console.WriteLine($"Available: {sheet.Name}");
}
$vbLabelText   $csharpLabel

C#에서 새 Excel 문서를 만드는 방법은 무엇인가요?

원하는 파일 형식으로 WorkBook 객체를 구성하여 새 Excel 문서를 만드세요. IronXL은 최신 XLSX 형식과 기존 XLS 형식을 모두 지원합니다.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
using IronXL;

// Create new XLSX workbook (recommended format)
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Set workbook metadata
workBook.Metadata.Author = "Your Application";
workBook.Metadata.Comments = "Generated by IronXL";

// Create new XLS workbook for legacy support
WorkBook legacyWorkBook = WorkBook.Create(ExcelFileFormat.XLS);

// Save the workbook
workBook.SaveAs("NewDocument.xlsx");
$vbLabelText   $csharpLabel

참고: ExcelFileFormat.XLS는 Excel 2003 이하 버전과의 호환성이 필요한 경우에만 사용하십시오.

엑셀 문서에 워크시트를 추가하려면 어떻게 해야 하나요?

IronXL WorkBook에는 워크시트 모음이 포함되어 있습니다. 이러한 구조를 이해하면 여러 시트로 구성된 엑셀 파일을 만들 때 도움이 됩니다.

여러 워크시트가 포함된 통합 문서를 보여주는 다이어그램 IronXL에서 여러 워크시트 개체를 포함하는 워크북 구조의 시각적 표현입니다.

CreateWorkSheet()를 사용하여 새 워크시트를 만드세요:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
using IronXL;

// Create multiple worksheets with descriptive names
WorkSheet summarySheet = workBook.CreateWorkSheet("Summary");
WorkSheet dataSheet = workBook.CreateWorkSheet("RawData");
WorkSheet chartSheet = workBook.CreateWorkSheet("Charts");

// Set the active worksheet
workBook.SetActiveTab(0); // Makes "Summary" the active sheet

// Access default worksheet (first sheet)
WorkSheet defaultSheet = workBook.DefaultWorkSheet;
$vbLabelText   $csharpLabel

셀 값을 읽고 편집하는 방법은 무엇인가요?

단일 셀을 읽고 편집합니다.

워크시트의 인덱서 속성을 통해 개별 셀에 접근할 수 있습니다. IronXL의 Cell 클래스는 강력한 형식의 값 속성을 제공합니다.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
using IronXL;
using System;
using System.Linq;

// Load workbook and get worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Access cell B1
IronXL.Cell cell = workSheet["B1"].First();

// Read cell value with type safety
string textValue = cell.StringValue;
int intValue = cell.IntValue;
decimal decimalValue = cell.DecimalValue;
DateTime? dateValue = cell.DateTimeValue;

// Check cell data type
if (cell.IsNumeric)
{
    Console.WriteLine($"Numeric value: {cell.DecimalValue}");
}
else if (cell.IsText)
{
    Console.WriteLine($"Text value: {cell.StringValue}");
}
$vbLabelText   $csharpLabel

Cell 클래스는 다양한 데이터 유형에 대한 여러 속성을 제공하며, 가능한 경우 값을 자동으로 변환합니다. 셀 작업에 대한 자세한 내용은 셀 서식 튜토리얼을 참조하세요.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Write different data types to cells
workSheet["A1"].Value = "Product Name";     // String
workSheet["B1"].Value = 99.95m;             // Decimal
workSheet["C1"].Value = DateTime.Today;     // Date
workSheet["D1"].Formula = "=B1*1.2";        // Formula
                                            // Format cells
workSheet["B1"].FormatString = "$#,##0.00"; // Currency format
workSheet["C1"].FormatString = "yyyy-MM-dd";// Date format
                                            // Save changes
workBook.Save();
$vbLabelText   $csharpLabel

셀 범위를 어떻게 사용할 수 있나요?

Range 클래스는 셀 모음을 나타내며, 이를 통해 Excel 데이터에 대한 일괄 작업을 수행할 수 있습니다.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
using IronXL;
using Range = IronXL.Range;

// Select range using Excel notation
Range range = workSheet["D2:D101"];

// Alternative: Use Range class for dynamic selection
Range dynamicRange = workSheet.GetRange("D2:D101"); // Row 2_101, Column D

// Perform bulk operations
range.Value = 0; // Set all cells to 0
$vbLabelText   $csharpLabel

셀 개수를 알고 있을 때 루프를 사용하여 효율적으로 범위를 처리합니다.

// Data validation example
public class ValidationResult
{
    public int Row { get; set; }
    public string PhoneError { get; set; }
    public string EmailError { get; set; }
    public string DateError { get; set; }
    public bool IsValid => string.IsNullOrEmpty(PhoneError) && 
                           string.IsNullOrEmpty(EmailError) && 
                           string.IsNullOrEmpty(DateError);
}

// Validate data in rows 2-101
var results = new List<ValidationResult>();

for (int row = 2; row <= 101; row++)
{
    var result = new ValidationResult { Row = row };

    // Get row data efficiently
    var phoneCell = workSheet[$"B{row}"];
    var emailCell = workSheet[$"D{row}"];
    var dateCell = workSheet[$"E{row}"];

    // Validate phone number
    if (!IsValidPhoneNumber(phoneCell.StringValue))
        result.PhoneError = "Invalid phone format";

    // Validate email
    if (!IsValidEmail(emailCell.StringValue))
        result.EmailError = "Invalid email format";

    // Validate date
    if (!dateCell.IsDateTime)
        result.DateError = "Invalid date format";

    results.Add(result);
}

// Helper methods
bool IsValidPhoneNumber(string phone) => 
    System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");

bool IsValidEmail(string email) => 
    email.Contains("@") && email.Contains(".");
// Data validation example
public class ValidationResult
{
    public int Row { get; set; }
    public string PhoneError { get; set; }
    public string EmailError { get; set; }
    public string DateError { get; set; }
    public bool IsValid => string.IsNullOrEmpty(PhoneError) && 
                           string.IsNullOrEmpty(EmailError) && 
                           string.IsNullOrEmpty(DateError);
}

// Validate data in rows 2-101
var results = new List<ValidationResult>();

for (int row = 2; row <= 101; row++)
{
    var result = new ValidationResult { Row = row };

    // Get row data efficiently
    var phoneCell = workSheet[$"B{row}"];
    var emailCell = workSheet[$"D{row}"];
    var dateCell = workSheet[$"E{row}"];

    // Validate phone number
    if (!IsValidPhoneNumber(phoneCell.StringValue))
        result.PhoneError = "Invalid phone format";

    // Validate email
    if (!IsValidEmail(emailCell.StringValue))
        result.EmailError = "Invalid email format";

    // Validate date
    if (!dateCell.IsDateTime)
        result.DateError = "Invalid date format";

    results.Add(result);
}

// Helper methods
bool IsValidPhoneNumber(string phone) => 
    System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");

bool IsValidEmail(string email) => 
    email.Contains("@") && email.Contains(".");
$vbLabelText   $csharpLabel

엑셀 스프레드시트에 수식을 추가하는 방법은 무엇인가요?

Formula 속성을 사용하여 Excel 수식을 적용합니다. IronXL은 표준 Excel 수식 구문을 지원합니다.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
using IronXL;

// Add formulas to calculate percentages
int lastRow = 50;
for (int row = 2; row < lastRow; row++)
{
    // Calculate percentage: current value / total
    workSheet[$"C{row}"].Formula = $"=B{row}/B{lastRow}";
    // Format as percentage
    workSheet[$"C{row}"].FormatString = "0.00%";
}
// Add summary formulas
workSheet["B52"].Formula = "=SUM(B2:B50)";      // Sum
workSheet["B53"].Formula = "=AVERAGE(B2:B50)";   // Average
workSheet["B54"].Formula = "=MAX(B2:B50)";       // Maximum
workSheet["B55"].Formula = "=MIN(B2:B50)";       // Minimum
                                                 // Force formula evaluation
workBook.EvaluateAll();
$vbLabelText   $csharpLabel

기존 수식을 수정하려면 Excel 수식 튜토리얼을 참조하세요.

스프레드시트 데이터의 유효성을 어떻게 검증할 수 있나요?

IronXL은 스프레드시트에 대한 포괄적인 데이터 유효성 검사를 가능하게 합니다. 이 예제는 외부 라이브러리와 C# 내장 기능을 사용하여 전화번호, 이메일 주소 및 날짜의 유효성을 검사합니다.

using System.Text.RegularExpressions;
using IronXL;

// Validation implementation
for (int i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get cells for current person
    var cells = workSheet[$"A{i}:E{i}"].ToList();

    // Validate phone (column B)
    string phone = cells[1].StringValue;
    if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
    {
        result.PhoneNumberErrorMessage = "Invalid phone format";
    }

    // Validate email (column D)
    string email = cells[3].StringValue;
    if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
    {
        result.EmailErrorMessage = "Invalid email address";
    }

    // Validate date (column E)
    if (!cells[4].IsDateTime)
    {
        result.DateErrorMessage = "Invalid date format";
    }
}
using System.Text.RegularExpressions;
using IronXL;

// Validation implementation
for (int i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get cells for current person
    var cells = workSheet[$"A{i}:E{i}"].ToList();

    // Validate phone (column B)
    string phone = cells[1].StringValue;
    if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
    {
        result.PhoneNumberErrorMessage = "Invalid phone format";
    }

    // Validate email (column D)
    string email = cells[3].StringValue;
    if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
    {
        result.EmailErrorMessage = "Invalid email address";
    }

    // Validate date (column E)
    if (!cells[4].IsDateTime)
    {
        result.DateErrorMessage = "Invalid date format";
    }
}
$vbLabelText   $csharpLabel

유효성 검사 결과를 새 워크시트에 저장합니다.

// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");

// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";

// Output validation results
for (int i = 0; i < results.Count; i++)
{
    var result = results[i];
    int outputRow = i + 2;

    resultsSheet[$"A{outputRow}"].Value = result.Row;
    resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
    resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
    resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";

    // Highlight invalid rows
    if (!result.IsValid)
    {
        resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
    }
}

// Auto-fit columns
for (int col = 0; col < 5; col++)
{
    resultsSheet.AutoSizeColumn(col);
}

// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");

// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";

// Output validation results
for (int i = 0; i < results.Count; i++)
{
    var result = results[i];
    int outputRow = i + 2;

    resultsSheet[$"A{outputRow}"].Value = result.Row;
    resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
    resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
    resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";

    // Highlight invalid rows
    if (!result.IsValid)
    {
        resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
    }
}

// Auto-fit columns
for (int col = 0; col < 5; col++)
{
    resultsSheet.AutoSizeColumn(col);
}

// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
$vbLabelText   $csharpLabel

엑셀 데이터를 데이터베이스로 내보내는 방법은 무엇인가요?

IronXL을 Entity Framework와 함께 사용하여 스프레드시트 데이터를 데이터베이스로 직접 내보낼 수 있습니다. 이 예제는 국가별 GDP 데이터를 SQLite로 내보내는 방법을 보여줍니다.

using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;

// Define entity model
public class Country
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Range(0, double.MaxValue)]
    public decimal GDP { get; set; }

    public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;

// Define entity model
public class Country
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Range(0, double.MaxValue)]
    public decimal GDP { get; set; }

    public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
$vbLabelText   $csharpLabel

데이터베이스 작업을 위한 Entity Framework 컨텍스트를 구성합니다.

public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure SQLite connection
        optionsBuilder.UseSqlite("Data Source=CountryGDP.db");

        // Enable sensitive data logging in development
        #if DEBUG
        optionsBuilder.EnableSensitiveDataLogging();
        #endif
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure decimal precision
        modelBuilder.Entity<Country>()
            .Property(c => c.GDP)
            .HasPrecision(18, 2);
    }
}
public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure SQLite connection
        optionsBuilder.UseSqlite("Data Source=CountryGDP.db");

        // Enable sensitive data logging in development
        #if DEBUG
        optionsBuilder.EnableSensitiveDataLogging();
        #endif
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure decimal precision
        modelBuilder.Entity<Country>()
            .Property(c => c.GDP)
            .HasPrecision(18, 2);
    }
}
$vbLabelText   $csharpLabel

참고해 주세요참고: 다른 데이터베이스를 사용하려면 해당 NuGet 패키지(예: SQL Server용 Microsoft.EntityFrameworkCore.SqlServer)를 설치하고 연결 구성을 accordingly 수정하십시오.

엑셀 데이터를 데이터베이스로 가져오기:

using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;

public async Task ImportGDPDataAsync()
{
    try
    {
        // Load Excel file
        var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
        var workSheet = workBook.GetWorkSheet("GDPByCountry");

        using (var context = new CountryContext())
        {
            // Ensure database exists
            await context.Database.EnsureCreatedAsync();

            // Clear existing data (optional)
            await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");

            // Import data with progress tracking
            int totalRows = 213;
            for (int row = 2; row <= totalRows; row++)
            {
                // Read country data
                var countryName = workSheet[$"A{row}"].StringValue;
                var gdpValue = workSheet[$"B{row}"].DecimalValue;

                // Skip empty rows
                if (string.IsNullOrWhiteSpace(countryName))
                    continue;

                // Create and add entity
                var country = new Country
                {
                    Name = countryName.Trim(),
                    GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
                };

                await context.Countries.AddAsync(country);

                // Save in batches for performance
                if (row % 50 == 0)
                {
                    await context.SaveChangesAsync();
                    Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
                }
            }

            // Save remaining records
            await context.SaveChangesAsync();
            Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Import failed: {ex.Message}");
        throw;
    }
}
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;

public async Task ImportGDPDataAsync()
{
    try
    {
        // Load Excel file
        var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
        var workSheet = workBook.GetWorkSheet("GDPByCountry");

        using (var context = new CountryContext())
        {
            // Ensure database exists
            await context.Database.EnsureCreatedAsync();

            // Clear existing data (optional)
            await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");

            // Import data with progress tracking
            int totalRows = 213;
            for (int row = 2; row <= totalRows; row++)
            {
                // Read country data
                var countryName = workSheet[$"A{row}"].StringValue;
                var gdpValue = workSheet[$"B{row}"].DecimalValue;

                // Skip empty rows
                if (string.IsNullOrWhiteSpace(countryName))
                    continue;

                // Create and add entity
                var country = new Country
                {
                    Name = countryName.Trim(),
                    GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
                };

                await context.Countries.AddAsync(country);

                // Save in batches for performance
                if (row % 50 == 0)
                {
                    await context.SaveChangesAsync();
                    Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
                }
            }

            // Save remaining records
            await context.SaveChangesAsync();
            Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Import failed: {ex.Message}");
        throw;
    }
}
$vbLabelText   $csharpLabel

API 데이터를 엑셀 스프레드시트로 가져오려면 어떻게 해야 하나요?

IronXL을 HTTP 클라이언트와 결합하여 실시간 API 데이터로 스프레드시트를 채우세요. 이 예제는 RestClient.Net을 사용하여 국가 데이터를 가져옵니다.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;

// Define data model matching API response
public class RestCountry
{
    public string Name { get; set; }
    public long Population { get; set; }
    public string Region { get; set; }
    public string NumericCode { get; set; }
    public List<Language> Languages { get; set; }
}

public class Language
{
    public string Name { get; set; }
    public string NativeName { get; set; }
}

// Fetch and process API data
public async Task ImportCountryDataAsync()
{
    using var httpClient = new HttpClient();

    try
    {
        // Call REST API
        var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
        var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);

        // Create new workbook
        var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        var workSheet = workBook.CreateWorkSheet("Countries");

        // Add headers with styling
        string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
        for (int col = 0; col < headers.Length; col++)
        {
            var headerCell = workSheet[0, col];
            headerCell.Value = headers[col];
            headerCell.Style.Font.Bold = true;
            headerCell.Style.SetBackgroundColor("#366092");
            headerCell.Style.Font.Color = "#FFFFFF";
        }

        // Import country data
        await ProcessCountryData(countries, workSheet);

        // Save workbook
        workBook.SaveAs("CountriesFromAPI.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"API import failed: {ex.Message}");
    }
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;

// Define data model matching API response
public class RestCountry
{
    public string Name { get; set; }
    public long Population { get; set; }
    public string Region { get; set; }
    public string NumericCode { get; set; }
    public List<Language> Languages { get; set; }
}

public class Language
{
    public string Name { get; set; }
    public string NativeName { get; set; }
}

// Fetch and process API data
public async Task ImportCountryDataAsync()
{
    using var httpClient = new HttpClient();

    try
    {
        // Call REST API
        var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
        var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);

        // Create new workbook
        var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        var workSheet = workBook.CreateWorkSheet("Countries");

        // Add headers with styling
        string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
        for (int col = 0; col < headers.Length; col++)
        {
            var headerCell = workSheet[0, col];
            headerCell.Value = headers[col];
            headerCell.Style.Font.Bold = true;
            headerCell.Style.SetBackgroundColor("#366092");
            headerCell.Style.Font.Color = "#FFFFFF";
        }

        // Import country data
        await ProcessCountryData(countries, workSheet);

        // Save workbook
        workBook.SaveAs("CountriesFromAPI.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"API import failed: {ex.Message}");
    }
}
$vbLabelText   $csharpLabel

API는 다음과 같은 형식의 JSON 데이터를 반환합니다.

중첩된 언어 배열을 포함하는 국가 데이터를 보여주는 JSON 응답 구조 계층적 국가 정보를 보여주는 REST 국가 API의 JSON 응답 예시입니다.

API 데이터를 처리하고 엑셀에 기록합니다.

private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
    for (int i = 0; i < countries.Count; i++)
    {
        var country = countries[i];
        int row = i + 1; // Start from row 1 (after headers)

        // Write basic country data
        workSheet[$"A{row}"].Value = country.Name;
        workSheet[$"B{row}"].Value = country.Population;
        workSheet[$"C{row}"].Value = country.Region;
        workSheet[$"D{row}"].Value = country.NumericCode;

        // Format population with thousands separator
        workSheet[$"B{row}"].FormatString = "#,##0";

        // Add up to 3 languages
        for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
        {
            var language = country.Languages[langIndex];
            string columnLetter = ((char)('E' + langIndex)).ToString();
            workSheet[$"{columnLetter}{row}"].Value = language.Name;
        }

        // Add conditional formatting for regions
        if (country.Region == "Europe")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
        }
        else if (country.Region == "Asia")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
        }

        // Show progress every 50 countries
        if (i % 50 == 0)
        {
            Console.WriteLine($"Processed {i} of {countries.Count} countries");
        }
    }

    // Auto-size all columns
    for (int col = 0; col < 7; col++)
    {
        workSheet.AutoSizeColumn(col);
    }
}
private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
    for (int i = 0; i < countries.Count; i++)
    {
        var country = countries[i];
        int row = i + 1; // Start from row 1 (after headers)

        // Write basic country data
        workSheet[$"A{row}"].Value = country.Name;
        workSheet[$"B{row}"].Value = country.Population;
        workSheet[$"C{row}"].Value = country.Region;
        workSheet[$"D{row}"].Value = country.NumericCode;

        // Format population with thousands separator
        workSheet[$"B{row}"].FormatString = "#,##0";

        // Add up to 3 languages
        for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
        {
            var language = country.Languages[langIndex];
            string columnLetter = ((char)('E' + langIndex)).ToString();
            workSheet[$"{columnLetter}{row}"].Value = language.Name;
        }

        // Add conditional formatting for regions
        if (country.Region == "Europe")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
        }
        else if (country.Region == "Asia")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
        }

        // Show progress every 50 countries
        if (i % 50 == 0)
        {
            Console.WriteLine($"Processed {i} of {countries.Count} countries");
        }
    }

    // Auto-size all columns
    for (int col = 0; col < 7; col++)
    {
        workSheet.AutoSizeColumn(col);
    }
}
$vbLabelText   $csharpLabel

객체 참조 및 리소스

IronXL API 참조 문서를 통해 자세한 클래스 설명과 고급 기능을 확인해 보세요.

엑셀 작업에 대한 추가 튜토리얼:

요약

IronXl.Excel은 다양한 형식의 Excel 파일을 읽고 조작하기 위한 포괄적인 .NET 라이브러리입니다. 이 프로그램은 Microsoft Excel 이나 Interop 설치 없이 독립적으로 작동합니다.

클라우드 기반 스프레드시트 조작을 위해서는 IronXL의 로컬 파일 기능을 보완하는 .NET용 Google Sheets API 클라이언트 라이브러리 도 살펴보는 것이 좋습니다.

C# 프로젝트에 Excel 자동화 기능을 구현할 준비가 되셨나요? IronXL을 다운로드 하거나 프로덕션 사용을 위한 라이선스 옵션을 살펴보세요.

자주 묻는 질문

Microsoft Office를 사용하지 않고 C#에서 Excel 파일을 읽는 방법은 무엇인가요?

IronXL을 사용하면 Microsoft Office 없이도 C#에서 Excel 파일을 읽을 수 있습니다. IronXL은 WorkBook.Load() 와 같은 메서드를 제공하여 Excel 파일을 열고 직관적인 구문을 사용하여 데이터에 접근하고 조작할 수 있도록 해줍니다.

C#에서 읽을 수 있는 Excel 파일 형식은 무엇인가요?

IronXL을 사용하면 C#에서 XLS 및 XLSX 파일 형식을 모두 읽을 수 있습니다. 이 라이브러리는 파일 형식을 자동으로 감지하고 WorkBook.Load() 메서드를 사용하여 적절하게 처리합니다.

C#에서 Excel 데이터의 유효성을 검사하는 방법은 무엇인가요?

IronXL을 사용하면 셀을 반복하고 이메일에 대한 정규 표현식이나 사용자 지정 유효성 검사 함수와 같은 논리를 적용하여 C#에서 Excel 데이터를 프로그래밍 방식으로 검증할 수 있습니다. CreateWorkSheet() 함수를 사용하여 보고서를 생성할 수 있습니다.

C#을 사용하여 Excel의 데이터를 SQL 데이터베이스로 내보내는 방법은 무엇입니까?

Excel에서 SQL 데이터베이스로 데이터를 내보내려면 IronXL을 사용하여 WorkBook.Load()GetWorkSheet() 메서드로 Excel 데이터를 읽은 다음 Entity Framework를 사용하여 셀을 반복하면서 데이터를 데이터베이스로 전송합니다.

Excel 기능을 ASP.NET Core 애플리케이션과 통합할 수 있을까요?

네, IronXL은 ASP.NET Core 애플리케이션과의 통합을 지원합니다. 컨트롤러에서 WorkBookWorkSheet 클래스를 사용하여 Excel 파일 업로드, 보고서 생성 등을 처리할 수 있습니다.

C#을 사용하여 엑셀 스프레드시트에 수식을 추가하는 것이 가능할까요?

IronXL을 사용하면 Excel 스프레드시트에 수식을 프로그래밍 방식으로 추가할 수 있습니다. Formula 속성을 사용하여 cell.Formula = "=SUM(A1:A10)" 과 같이 수식을 설정하고 workBook.EvaluateAll() 사용하여 결과를 계산할 수 있습니다.

REST API에서 가져온 데이터로 엑셀 파일을 채우는 방법은 무엇인가요?

REST API에서 가져온 데이터로 Excel 파일을 채우려면 IronXL을 HTTP 클라이언트와 함께 사용하여 API 데이터를 가져온 다음 sheet["A1"].Value 같은 메서드를 사용하여 Excel에 씁니다. IronXL은 Excel 서식과 구조를 관리합니다.

실제 운영 환경에서 Excel 라이브러리를 사용하기 위한 라이선스 옵션은 무엇인가요?

IronXL은 개발 목적으로 무료 평가판을 제공하며, 상용 라이선스는 749달러부터 시작합니다. 이 라이선스에는 전용 기술 지원이 포함되며, 추가 Office 라이선스 없이 다양한 환경에 배포할 수 있습니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

시작할 준비 되셨나요?
Nuget 다운로드 1,913,565 | 버전: 2026.3 방금 출시되었습니다
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package IronXL.Excel
샘플을 실행하세요 데이터가 스프레드시트로 변환되는 것을 지켜보세요.