Interop 없이 C#에서 xlsx 파일 읽기 및 엑셀 데이터 추출 완전 가이드
Microsoft Office 설치 없이도 xlsx 파일의 스프레드시트 데이터를 읽고, 유효성을 검사하고, 엑셀 데이터 추출을 수행할 수 있는 강력한 .NET 라이브러리인 IronXL을 사용하여 C#에서 Excel 파일을 능숙하게 조작하는 방법을 알아보세요. 이 종합 튜토리얼은 데이터 유효성 검사, 데이터베이스 변환 및 REST API 통합을 포함한 실용적인 Excel 작업 방법을 보여줍니다.
빠른 시작: IronXL을 사용하여 한 줄로 셀 읽기
IronXL을 사용하면 단 한 줄의 코드로 Excel 통합 문서를 불러와 셀 값을 가져올 수 있습니다. 이 시스템은 사용 편의성을 고려하여 설계되었습니다. 상호 운용성도 없고 복잡한 설정도 필요 없으며, 데이터에 빠르게 액세스할 수 있습니다.
C#에서 IronXL을 사용하여 Excel 파일을 읽도록 설정하는 방법은 무엇인가요?
C# 프로젝트에서 Excel 파일을 읽도록 IronXL을 설정하는 데는 몇 분밖에 걸리지 않습니다. 이 라이브러리는 .XLS 및 .XLSX 형식을 모두 지원하므로 모든 Excel 관련 작업에 다용도로 사용할 수 있습니다.
시작하려면 다음 단계를 따르세요.
- 엑셀 파일을 읽기 위한 C# 라이브러리를 다운로드하세요 .
WorkBook.Load()를 사용하여 Excel 통합 문서를 로드하고 읽습니다.GetWorkSheet()방법을 사용하여 워크시트에 액세스합니다.sheet["A1"].Value와 같은 직관적인 구문을 사용하여 셀 값을 읽습니다.- 스프레드시트 데이터를 프로그램 방식으로 검증하고 처리합니다.
- 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 파일을 읽는 데 필요한 핵심 워크플로는 다음과 같습니다.
- NuGet 패키지를 통해 IronXL Excel 라이브러리를 설치하거나 .NET Excel DLL 을 다운로드하십시오.
WorkBook.Load()메서드를 사용하여 모든 XLS, XLSX 또는 CSV 문서를 읽을 수 있습니다.- 직관적인 구문을 사용하여 셀 값에 액세스합니다:
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}");
Imports IronXL
Imports System
Imports System.Linq
' Load Excel workbook from file path
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
' Access the first worksheet using LINQ
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Read integer value from cell A2
Dim cellValue As Integer = workSheet("A2").IntValue
Console.WriteLine($"Cell A2 value: {cellValue}")
' Iterate through a range of cells
For Each cell In workSheet("A2:A10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next
' Advanced Operations with LINQ
' Calculate sum using built_in Sum() method
Dim sum As Decimal = workSheet("A2:A10").Sum()
' Find maximum value using LINQ
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
' Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}")
Console.WriteLine($"Maximum value: {max}")
이 코드는 IronXL의 주요 기능 몇 가지를 보여줍니다. 워크북 불러오기, 주소를 이용한 셀 접근, 범위 순회, 그리고 계산 수행 등이 포함됩니다. WorkBook.Load() 메서드는 파일 형식을 지능적으로 감지하는 반면, 범위 구문 ["A2:A10"]은 Excel과 유사한 셀 선택 기능을 제공합니다. LINQ 통합을 통해 셀 컬렉션에 대한 강력한 데이터 쿼리 및 집계가 가능합니다.
이 튜토리얼의 코드 예제는 서로 다른 데이터 시나리오를 보여주는 세 가지 샘플 Excel 스프레드시트를 사용합니다.
본 튜토리얼에서는 IronXL의 다양한 작업 방법을 설명하기 위해 샘플 Excel 파일(GDP.xlsx, People.xlsx, PopulationByState.xlsx)을 사용합니다.
IronXL C# 라이브러리는 어떻게 설치할 수 있나요?
IronXL.Excel 라이브러리를 설치하면 .NET Framework 프로젝트에 포괄적인 Excel 기능을 추가할 수 있습니다. NuGet 설치 또는 수동 DLL 통합 중에서 선택하십시오.
IronXL NuGet Install-Package
- Visual Studio에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 "NuGet 패키지 관리"를 선택합니다.
- 찾아보기 탭에서 "IronXL.Excel"을 검색하세요.
- 설치 버튼을 클릭하여 IronXL을 프로젝트에 추가하세요.
Visual Studio의 NuGet 패키지 관리자를 통해 IronXL을 설치하면 종속성 관리가 자동으로 이루어집니다.
또는 패키지 관리자 콘솔을 사용하여 IronXL을 설치하십시오.
- 패키지 관리자 콘솔을 엽니다(도구 → NuGet 패키지 관리자 → 패키지 관리자 콘솔).
- 설치 명령을 실행하세요:
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");
Imports IronXL
Imports System
Imports System.Linq
' Load Excel file from specified path
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\GDP.xlsx")
Console.WriteLine("Workbook loaded successfully.")
' Access specific worksheet by name
Dim sheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Read and display cell value
Dim cellValue As String = sheet("A1").StringValue
Console.WriteLine($"Cell A1 contains: {cellValue}")
' Perform additional operations
' Count non_empty cells in column A
Dim rowCount As Integer = sheet("A:A").Count(Function(cell) Not cell.IsEmpty)
Console.WriteLine($"Column A has {rowCount} non_empty cells")
각 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}");
}
Imports IronXL
Imports System
' Get worksheet by name
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
Console.WriteLine("Worksheet 'GDPByCountry' not found")
' List available worksheets
For Each sheet In workBook.WorkSheets
Console.WriteLine($"Available: {sheet.Name}")
Next
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");
Imports IronXL
' Create new XLSX workbook (recommended format)
Private workBook As 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
Dim legacyWorkBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
' Save the workbook
workBook.SaveAs("NewDocument.xlsx")
참고: 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;
Imports IronXL
' Create multiple worksheets with descriptive names
Dim summarySheet As WorkSheet = workBook.CreateWorkSheet("Summary")
Dim dataSheet As WorkSheet = workBook.CreateWorkSheet("RawData")
Dim chartSheet As WorkSheet = workBook.CreateWorkSheet("Charts")
' Set the active worksheet
workBook.SetActiveTab(0) ' Makes "Summary" the active sheet
' Access default worksheet (first sheet)
Dim defaultSheet As WorkSheet = workBook.DefaultWorkSheet
셀 값을 읽고 편집하는 방법은 무엇인가요?
단일 셀을 읽고 편집합니다.
워크시트의 인덱서 속성을 통해 개별 셀에 접근할 수 있습니다. 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}");
}
Imports IronXL
Imports System
Imports System.Linq
' Load workbook and get worksheet
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
' Access cell B1
Dim cell As IronXL.Cell = workSheet("B1").First()
' Read cell value with type safety
Dim textValue As String = cell.StringValue
Dim intValue As Integer = cell.IntValue
Dim decimalValue As Decimal = cell.DecimalValue
Dim dateValue As DateTime? = cell.DateTimeValue
' Check cell data type
If cell.IsNumeric Then
Console.WriteLine($"Numeric value: {cell.DecimalValue}")
ElseIf cell.IsText Then
Console.WriteLine($"Text value: {cell.StringValue}")
End If
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();
' Write different data types to cells
workSheet("A1").Value = "Product Name" ' String
workSheet("B1").Value = 99.95D ' 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()
셀 범위를 어떻게 사용할 수 있나요?
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
Imports IronXL
' Select range using Excel notation
Dim range As Range = workSheet("D2:D101")
' Alternative: Use Range class for dynamic selection
Dim dynamicRange As Range = workSheet.GetRange("D2:D101") ' Row 2_101, Column D
' Perform bulk operations
range.Value = 0 ' Set all cells to 0
셀 개수를 알고 있을 때 루프를 사용하여 효율적으로 범위를 처리합니다.
// 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(".");
' Data validation example
Public Class ValidationResult
Public Property Row() As Integer
Public Property PhoneError() As String
Public Property EmailError() As String
Public Property DateError() As String
Public ReadOnly Property IsValid() As Boolean
Get
Return String.IsNullOrEmpty(PhoneError) AndAlso String.IsNullOrEmpty(EmailError) AndAlso String.IsNullOrEmpty(DateError)
End Get
End Property
End Class
' Validate data in rows 2-101
Private results = New List(Of ValidationResult)()
For row As Integer = 2 To 101
Dim result = New ValidationResult With {.Row = row}
' Get row data efficiently
Dim phoneCell = workSheet($"B{row}")
Dim emailCell = workSheet($"D{row}")
Dim dateCell = workSheet($"E{row}")
' Validate phone number
If Not IsValidPhoneNumber(phoneCell.StringValue) Then
result.PhoneError = "Invalid phone format"
End If
' Validate email
If Not IsValidEmail(emailCell.StringValue) Then
result.EmailError = "Invalid email format"
End If
' Validate date
If Not dateCell.IsDateTime Then
result.DateError = "Invalid date format"
End If
results.Add(result)
Next row
' Helper methods
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'bool IsValidPhoneNumber(string phone)
'{
' Return System.Text.RegularExpressions.Regex.IsMatch(phone, "^\d{3}-\d{3}-\d{4}$");
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'bool IsValidEmail(string email)
'{
' Return email.Contains("@") && email.Contains(".");
'}
엑셀 스프레드시트에 수식을 추가하는 방법은 무엇인가요?
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();
Imports IronXL
' Add formulas to calculate percentages
Dim lastRow As Integer = 50
For row As Integer = 2 To lastRow - 1
' Calculate percentage: current value / total
workSheet($"C{row}").Formula = $"=B{row}/B{lastRow}"
' Format as percentage
workSheet($"C{row}").FormatString = "0.00%"
Next
' 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()
기존 수식을 수정하려면 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";
}
}
Imports System.Text.RegularExpressions
Imports IronXL
' Validation implementation
For i As Integer = 2 To 101
Dim result = New PersonValidationResult With {.Row = i}
results.Add(result)
' Get cells for current person
Dim cells = workSheet($"A{i}:E{i}").ToList()
' Validate phone (column B)
Dim phone As String = cells(1).StringValue
If Not Regex.IsMatch(phone, "^\+?1?\d{10,14}$") Then
result.PhoneNumberErrorMessage = "Invalid phone format"
End If
' Validate email (column D)
Dim email As String = cells(3).StringValue
If Not Regex.IsMatch(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$") Then
result.EmailErrorMessage = "Invalid email address"
End If
' Validate date (column E)
If Not cells(4).IsDateTime Then
result.DateErrorMessage = "Invalid date format"
End If
Next i
유효성 검사 결과를 새 워크시트에 저장합니다.
// 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");
' Create results worksheet
Dim 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 i As Integer = 0 To results.Count - 1
Dim result = results(i)
Dim outputRow As Integer = i + 2
resultsSheet($"A{outputRow}").Value = result.Row
resultsSheet($"B{outputRow}").Value = If(result.IsValid, "Yes", "No")
resultsSheet($"C{outputRow}").Value = If(result.PhoneNumberErrorMessage, "")
resultsSheet($"D{outputRow}").Value = If(result.EmailErrorMessage, "")
resultsSheet($"E{outputRow}").Value = If(result.DateErrorMessage, "")
' Highlight invalid rows
If Not result.IsValid Then
resultsSheet($"A{outputRow}:E{outputRow}").Style.SetBackgroundColor("#FFE6E6")
End If
Next i
' Auto-fit columns
For col As Integer = 0 To 4
resultsSheet.AutoSizeColumn(col)
Next col
' Save validated workbook
workBook.SaveAs("Spreadsheets\PeopleValidated.xlsx")
엑셀 데이터를 데이터베이스로 내보내는 방법은 무엇인가요?
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;
}
Imports System
Imports System.ComponentModel.DataAnnotations
Imports Microsoft.EntityFrameworkCore
Imports IronXL
' Define entity model
Public Class Country
<Key>
Public Property Id() As Guid = Guid.NewGuid()
<Required>
<MaxLength(100)>
Public Property Name() As String
<Range(0, Double.MaxValue)>
Public Property GDP() As Decimal
Public Property ImportedDate() As DateTime = DateTime.UtcNow
End Class
데이터베이스 작업을 위한 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);
}
}
Public Class CountryContext
Inherits DbContext
Public Property Countries() As DbSet(Of Country)
Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
' Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db")
' Enable sensitive data logging in development
#If DEBUG Then
optionsBuilder.EnableSensitiveDataLogging()
#End If
End Sub
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As ModelBuilder)
' Configure decimal precision
modelBuilder.Entity(Of Country)().Property(Function(c) c.GDP).HasPrecision(18, 2)
End Sub
End Class
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;
}
}
Imports System.Threading.Tasks
Imports IronXL
Imports Microsoft.EntityFrameworkCore
Public Async Function ImportGDPDataAsync() As Task
Try
' Load Excel file
Dim workBook = WorkBook.Load("Spreadsheets\GDP.xlsx")
Dim workSheet = workBook.GetWorkSheet("GDPByCountry")
Using 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
Dim totalRows As Integer = 213
Dim row As Integer = 2
Do While row <= totalRows
' Read country data
Dim countryName = workSheet($"A{row}").StringValue
Dim gdpValue = workSheet($"B{row}").DecimalValue
' Skip empty rows
If String.IsNullOrWhiteSpace(countryName) Then
row += 1
Continue Do
End If
' Create and add entity
Dim country As New Country With {
.Name = countryName.Trim(),
.GDP = gdpValue * 1_000_000
}
Await context.Countries.AddAsync(country)
' Save in batches for performance
If row Mod 50 = 0 Then
Await context.SaveChangesAsync()
Console.WriteLine($"Imported {row - 1} of {totalRows} countries")
End If
row += 1
Loop
' Save remaining records
Await context.SaveChangesAsync()
Console.WriteLine($"Successfully imported {Await context.Countries.CountAsync()} countries")
End Using
Catch ex As Exception
Console.WriteLine($"Import failed: {ex.Message}")
Throw
End Try
End Function
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}");
}
}
Imports System
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports IronXL
' Define data model matching API response
Public Class RestCountry
Public Property Name() As String
Public Property Population() As Long
Public Property Region() As String
Public Property NumericCode() As String
Public Property Languages() As List(Of Language)
End Class
Public Class Language
Public Property Name() As String
Public Property NativeName() As String
End Class
' Fetch and process API data
Public Async Function ImportCountryDataAsync() As Task
Dim httpClient As New HttpClient()
Try
' Call REST API
Dim response = Await httpClient.GetStringAsync("https://restcountries.com/v3.1/all")
Dim countries = JsonConvert.DeserializeObject(Of List(Of RestCountry))(response)
' Create new workbook
Dim workBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim workSheet = workBook.CreateWorkSheet("Countries")
' Add headers with styling
Dim headers() As String = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" }
For col As Integer = 0 To headers.Length - 1
Dim headerCell = workSheet(0, col)
headerCell.Value = headers(col)
headerCell.Style.Font.Bold = True
headerCell.Style.SetBackgroundColor("#366092")
headerCell.Style.Font.Color = "#FFFFFF"
Next col
' Import country data
Await ProcessCountryData(countries, workSheet)
' Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx")
Catch ex As Exception
Console.WriteLine($"API import failed: {ex.Message}")
End Try
End Function
API는 다음과 같은 형식의 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);
}
}
Private Async Function ProcessCountryData(ByVal countries As List(Of RestCountry), ByVal workSheet As WorkSheet) As Task
For i As Integer = 0 To countries.Count - 1
Dim country = countries(i)
Dim row As Integer = 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 langIndex As Integer = 0 To Math.Min(3, If(country.Languages?.Count, 0)) - 1
Dim language = country.Languages(langIndex)
Dim columnLetter As String = (ChrW(AscW("E"c) + langIndex)).ToString()
workSheet($"{columnLetter}{row}").Value = language.Name
Next langIndex
' Add conditional formatting for regions
If country.Region = "Europe" Then
workSheet($"C{row}").Style.SetBackgroundColor("#E6F3FF")
ElseIf country.Region = "Asia" Then
workSheet($"C{row}").Style.SetBackgroundColor("#FFF2E6")
End If
' Show progress every 50 countries
If i Mod 50 = 0 Then
Console.WriteLine($"Processed {i} of {countries.Count} countries")
End If
Next i
' Auto-size all columns
For col As Integer = 0 To 6
workSheet.AutoSizeColumn(col)
Next col
End Function
객체 참조 및 리소스
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 애플리케이션과의 통합을 지원합니다. 컨트롤러에서 WorkBook 및 WorkSheet 클래스를 사용하여 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 라이선스 없이 다양한 환경에 배포할 수 있습니다.

