푸터 콘텐츠로 바로가기
IRONXL 사용하여
IronXL을 사용하여 C#에서 CSV 파일을 읽는 방법

C#에서 CSV 파일 읽기: 튜토리얼

다양한 Excel 형식으로 작업할 때 종종 데이터를 읽은 후 프로그램적으로 재구성해야 할 필요가 있습니다. 이 기사에서는 CSV 파일을 읽고, C#에서 IronXL을 사용하여 Excel 스프레드시트에서 데이터를 파싱하는 방법을 배웁니다.

CSV란 무엇인가?

CSV는 간단한 데이터 형식이지만 많은 차이점이 있을 수 있습니다; C# 프로젝트에서 프로그램적으로 읽기 어려운 이유는 여러 구분자를 사용하여 데이터의 행 및 열을 구분하기 때문입니다. 이 기사는 IronXL 라이브러리를 사용하여 CSV 파일을 읽는 방법을 보여줍니다.


1. How to read a CSV File in C#

MVC, ASP.NET 또는 .NET Core에서 CSV 파일을 읽기 위해 IronXL을 사용하기 전에 설치해야 합니다. 이것은 간단한 절차입니다.

  1. Visual Studio에서 프로젝트 메뉴를 선택합니다.
  2. NuGet 패키지 관리
  3. IronXl.Excel 검색
  4. 설치

C#에서 CSV 파일 읽기: 튜토리얼, 그림 1: Visual Studio에서 NuGet 패키지 관리자에서 IronXL 검색 Visual Studio의 NuGet 패키지 관리자에서 IronXL 검색

C#에서 CSV 파일을 읽어야 할 때, IronXL은 완벽한 도구입니다. 아래 코드 세그먼트에서 보이는 것처럼, 쉼표 또는 다른 구분자가 있는 CSV 파일을 읽을 수 있습니다.

// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
$vbLabelText   $csharpLabel

산출:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 2: 쉼표 구분자가 있는 출력 CSV 파일 쉼표 구분자가 있는 CSV 파일 출력

코드 설명:

A WorkBook 개체가 생성됩니다. LoadCSV 메서드를 사용하여 CSV의 이름, 형식 및 CSV 파일에서 사용되는 구분자를 지정합니다. 이 경우, 구분자로 쉼표가 사용됩니다.

그런 다음 WorkSheet 개체가 생성됩니다. 여기서 CSV 파일의 내용이 저장됩니다. 파일은 새 이름과 형식으로 저장됩니다.

C#에서 CSV 파일 읽기: 튜토리얼, 그림 3: Microsoft Excel에 표시된 데이터 Microsoft Excel에서 표시된 데이터


2. Excel 파일을 위한 IronXL

IronXL을 사용하여 C#에서 Excel 파일 형식을 다루는 간소화된 방법으로 프로젝트에 사용하십시오. IronXL을 직접 다운로드하여 설치할 수 있습니다.. 또한, NuGet Install for Visual Studio를 사용할 수 있습니다. 소프트웨어는 개발을 위해 무료입니다.

dotnet add package IronXl.Excel

3. WorkBook 로드 및 WorkSheet 접근

WorkBook는 IronXL의 클래스이며, Excel 파일과 모든 기능에 완전한 접근을 제공합니다. 예를 들어, Excel 파일에 접근하려면 다음 코드를 사용합니다:

// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
$vbLabelText   $csharpLabel

Excel 파일의 특정 워크시트에 접근하기 위해 IronXL은 WorkSheet 클래스를 제공합니다.

// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
$vbLabelText   $csharpLabel

Excel 워크시트 ws을(를) 얻은 후에는 모든 유형의 데이터를 추출하고 모든 Excel 기능을 수행할 수 있습니다. Excel 워크시트 ws의 데이터는 다음 프로세스를 통해 접근할 수 있습니다:

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

4. DataTable로 Excel 워크시트 읽기

IronXL을 사용하면 Excel WorkSheet을(를) DataTable로 쉽게 작업할 수 있습니다.

DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
$vbLabelText   $csharpLabel

다음 네임스페이스를 사용하십시오:

using IronXL;
using System.Data;
using IronXL;
using System.Data;
$vbLabelText   $csharpLabel

다음 코드를 작성하십시오:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 4: DataTable 객체의 콘솔 출력 DataTable 객체의 콘솔 출력

이 예제에서는 Excel 파일을 DataSet로 사용하는 방법을 살펴보겠습니다.

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 5: DataSet 객체에서 시트 이름 접근 DataSet 객체에서 시트 이름 접근

이제 모든 Excel 시트를 대상으로 각 셀 값을 접근하는 또 다른 예제를 살펴보겠습니다. 여기서, 우리는 Excel 파일의 모든 워크시트에서 각 셀 값을 접근할 수 있습니다.

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 6: Dataset 객체의 콘솔 출력 DataSet 객체의 콘솔 출력

5. C# .NET에서 CSV 구문 분석

CSV 파일은 필드에서 줄 바꿈을 처리하는 방식이나 간단한 문자열 분할 접근을 완전히 차단하는 인용 부호로 필드를 감쌀 수 있는 방법에 문제가 많습니다. 최근에 나는 C# .NET에서 CSV를 사용하여 값을 쉼표로 구분하는 대신 커스터마이즈 가능한 구분자를 지정하는 옵션을 발견했습니다.

6. C# 레코드에서 CSV 데이터 읽기

이 과정은 다음 파일로 리더를 진행시킵니다. 우리는 TryGetField에서 CSV 필드 파일을 읽습니다. 우리는 CSV 파일의 필드 필드를 레코드 필드로 사용하여 읽기 기능을 사용합니다.

// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 7: DataTable의 콘솔 출력 DataTable에서의 콘솔 출력

7. Excel 파일에서 데이터 가져오기

이제 우리가 다양한 방법을 사용하여 열린 Excel WorkSheet에서 데이터를 쉽게 가져올 수 있습니다. 다음 예제에서 특정 셀 값을 액세스하고 이를 string로 파싱하는 방법을 볼 수 있습니다:

// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
$vbLabelText   $csharpLabel

위의 줄에서 ws는 2단계에서 정의된 WorkSheet입니다. 이것은 '간단한' 접근 방식이지만, Excel 파일 데이터를 액세스하는 방법에 대한 다른 예제도 읽을 수 있습니다.

8. How to Parse Excel Files in C#

응용 프로그램 빌드를 위해 Excel 스프레드시트를 사용할 때, 우리는 종종 데이터를 기반으로 결과를 분석하고 C# 내에서 Excel 파일 데이터를 필수 형식으로 구문 분석하여 올바른 결과를 얻어야 합니다. IronXL을 사용하여 C# 환경에서 서로 다른 형식으로 데이터를 구문 분석하는 것이 쉽게 이루어집니다; 아래의 단계를 참조하십시오.

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

9. Excel 데이터를 숫자 및 불리언 값으로 구문 분석하는 방법

이제 Excel 파일 데이터를 구문 분석하는 방법으로 이동합니다. 먼저 숫자 Excel 데이터를 처리하는 방법을 살펴보고, 이를 필요한 형식으로 구문 분석하는 방법을 살펴보겠습니다.

C#에서 CSV 파일 읽기: 튜토리얼, 그림 8: 각 데이터 형식에 대한 요약 테이블 각 데이터 유형에 대한 요약 테이블

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

이 코드는 다음 출력을 표시합니다:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 9: 올바른 데이터 유형의 콘솔 출력 올바른 데이터 유형으로 콘솔 출력

여기서 우리는 sample.xlsx Excel 파일의 값을 볼 수 있습니다:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 10: Excel에 올바른 데이터 형식 표시 Excel에서 올바른 데이터 유형 표시

Excel 파일 데이터를 Boolean 데이터 유형으로 파싱하려면 IronXL은 BoolValue 함수를 제공합니다. 다음과 같이 사용할 수 있습니다:

// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
$vbLabelText   $csharpLabel

10. Excel 파일을 C# 컬렉션으로 파싱하는 방법

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

10.1 Excel WorkSheet을(를) DataTable로 파싱하는 방법

IronXL의 뛰어난 기능 중 하나는 특정 Excel WorkSheet을(를) 쉽게 DataTable로 변환할 수 있다는 것입니다. 이 목적을 위해 IronXL의 .ToDataTable() 함수를 다음과 같이 사용할 수 있습니다:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
$vbLabelText   $csharpLabel

10.2 Excel 파일을 DataSet으로 파싱하는 방법

Excel 파일 전체를 DataSet으로 파싱하려면, 이를 위해 IronXL에서 .ToDataSet() 함수를 사용할 수 있습니다.

class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
$vbLabelText   $csharpLabel

10.3 특정 범위 내에서 Excel 데이터 읽기

IronXL은 특정 범위 내에서 Excel 파일 데이터를 읽기 위한 지능형 방법을 제공합니다. 범위는 행과 열 모두에 적용할 수 있습니다.

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

위의 코드는 다음 출력을 표시합니다:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 11: 범위 B3:B8의 모든 값에 접근하기 위한 콘솔 출력 B3:B8 범위의 모든 값에 대한 콘솔 출력

Excel 파일 sample.xlsx의 값:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 12: sample.xlsx의 데이터 표시 sample.xlsx의 데이터 표시

또한, IronXL은 스타일 및 테두리, 수학 함수, 조건부 서식 또는 사용 가능한 데이터로부터 차트를 생성하는 등의 많은 Excel 메서드와도 호환됩니다.

11. Excel 파일에서 Boolean 데이터를 읽는 방법

응용 프로그램 개발에서는 Excel 파일의 Boolean 데이터 유형을 기반으로 결정을 내려야 합니다.

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

이로부터 우리는 다음 출력을 얻습니다:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 13: Boolean 데이터 가져오기에서 콘솔 출력 Boolean 데이터 가져오기에서의 콘솔 출력

그리고 C1에서 C10까지의 값이 있는 Excel 파일 sample.xlsx:

C#에서 CSV 파일 읽기: 튜토리얼, 그림 14: 콘솔 출력과 비교할 Excel 샘플 콘솔 출력과 비교를 위한 Excel 샘플

12. 전체 Excel 워크시트를 읽는 방법

행과 열 인덱스를 사용하여 전체 Excel 워크시트를 읽는 것은 간단합니다. 이 목적을 위해 우리는 모든 행을 순회하기 위한 루프 하나와 특정 행의 모든 열을 순회하기 위한 두 번째 루프를 사용합니다. 그런 다음 전체 Excel 워크시트 내의 모든 셀 값을 쉽게 얻을 수 있습니다.

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 15: 모든 값을 읽은 후 콘솔 출력 모든 값 읽기에서의 콘솔 출력

13. Interop 없이 Excel 파일 읽기

IronXL은 C#과 .NET을 위한 Excel 라이브러리로, 개발자가 Microsoft.Office.Interop.Excel을 사용하지 않고도 XLS 및 XLSX 문서에서 Excel 데이터를 읽고 편집할 수 있도록 해줍니다.

이 API는 다음을 위해 Excel 파일을 직관적으로 생성, 읽기, 조작, 저장 및 내보낼 수 있게 해줍니다:

.NET Framework 4.5+ .NET Core 2+ .NET Standard Xamarin Windows Mobile Mono & Azure Cloud Hosting Blazor .NET MAUI

다음 네임스페이스를 추가하세요:

using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
$vbLabelText   $csharpLabel

이제 메인 함수 내에 다음 코드를 작성하세요.

class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
$vbLabelText   $csharpLabel

C#에서 CSV 파일 읽기: 튜토리얼, 그림 16: 각 셀의 콘솔 출력 각 셀의 콘솔 출력

IronXL은 또한 ASP.NET, MVC, Windows, macOS, Linux, iOS 및 Android 모바일 응용 프로그램 개발을 완벽하게 지원합니다.

14. 결론 및 Iron XL 특별 제공

C#에서의 CSV 파싱 외에도, IronXL은 단 두 줄의 코드로 CSV 파일을 Excel로 변환합니다!

C# 또는 VB.NET을 사용하면 Interop이 필요 없이 IronXL의 Excel API를 매우 쉽게 사용할 수 있습니다. Excel 스프레드시트를 읽고, 편집하고, 생성하거나 XLS/XLSX/CSV/TSV와 같은 다른 Excel 형식과 작업할 수 있습니다. 여러 프레임워크 지원을 통해 두 개 가격으로 5개의 제품을 구매할 수 있습니다. 추가 정보를 보려면 가격 페이지를 클릭하십시오.

C#에서 CSV 파일 읽기: 튜토리얼, 그림 17: Iron Suite의 5가지 제품 Iron Suite의 5개 제품

자주 묻는 질문

C#에서 CSV 파일을 어떻게 읽을 수 있나요?

C#에서 CSV 파일을 읽으려면 Visual Studio의 NuGet 통해 IronXL 라이브러리를 설치하면 됩니다. 설치 후에는 WorkBook.LoadCSV 메서드를 사용하여 CSV 파일을 로드하고 해석할 수 있습니다.

CSV란 무엇이며, C#에서 다루기가 복잡한 이유는 무엇일까요?

CSV는 간단한 데이터 형식이지만, 다양한 구분 기호 때문에 다루기가 복잡할 수 있습니다. IronXL C# 프로젝트에서 CSV 파일을 읽고 구문 분석하는 작업을 간소화합니다.

C#을 사용하여 CSV 파일을 Excel 파일로 변환할 수 있나요?

네, IronXL CSV 파일을 불러와 WorkBook.SaveAs 메서드를 사용하여 저장함으로써 CSV 파일을 XLS 또는 XLSX와 같은 Excel 형식으로 변환할 수 있습니다.

C# 프로젝트에 IronXL을 설치하는 방법은 무엇인가요?

Visual Studio의 NuGet 패키지 관리자를 사용하여 IronXL 설치할 수 있습니다. ' IronXL'을 검색하여 프로젝트에 추가하면 Excel 파일 작업을 시작할 수 있습니다.

C#에서 엑셀 셀 데이터를 특정 데이터 형식으로 파싱하는 것이 가능할까요?

네, IronXL 사용하면 Int32ValueBoolValue 와 같은 메서드를 사용하여 Excel 셀 값을 숫자 및 부울과 같은 특정 데이터 형식으로 구문 분석할 수 있습니다.

C#을 사용하여 Excel 시트의 특정 셀 범위에서 데이터를 읽으려면 어떻게 해야 합니까?

IronXL 사용하면 루프를 통해 범위를 순회하고 IronXL의 인덱싱 기능을 통해 셀 값에 접근하여 특정 셀의 데이터를 읽을 수 있습니다.

C#에서 Excel 워크시트를 DataTable로 변환하는 방법은 무엇인가요?

IronXL의 WorkSheet.ToDataTable 메서드를 사용하면 Excel 워크시트를 DataTable로 효율적으로 변환할 수 있습니다. 이 메서드는 워크시트를 파싱하여 데이터 조작에 적합한 DataTable 객체를 생성합니다.

엑셀 파일을 프로그램으로 읽으려면 Microsoft Office Interop이 필요한가요?

아니요, IronXL 사용하면 Microsoft Office Interop 없이도 Excel 파일을 읽고 조작할 수 있으므로 독립적이고 효율적인 솔루션입니다.

IronXL 사용하여 Excel 및 CSV 파일을 처리하는 데에는 어떤 장점이 있습니까?

IronXL 간편한 설치, Interop에 대한 의존성 없음, 다양한 Excel 형식 지원, 다양한 .NET Framework와의 호환성을 제공하여 CSV 및 Excel 파일 처리 생산성을 향상시킵니다.

C#에서 엑셀 워크시트 전체를 읽는 방법은 무엇인가요?

IronXL 사용하여 전체 Excel 워크시트를 읽으려면 중첩 루프를 사용하여 모든 행과 열을 순회하고 IronXL의 메서드를 사용하여 셀 값을 추출할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me