Excel 파일을 읽고 DataTable 및 데이터베이스로 데이터를 내보내는 C#

2024-01-25 07:12:20 Jack Du

C#에서 Excel 파일을 읽는 것은 데이터 분석, 보고 또는 데이터베이스 통합 등 많은 애플리케이션의 일반적인 요구 사항입니다. Microsoft의 Interop 라이브러리를 사용할 수 있지만, Excel 설치가 필요하다는 등의 제한이 있습니다. 대신, Interop 없이 Excel 파일을 읽고 쓸 수 있는 .NET 라이브러리인 Spire.XLS를 사용하는 더 효율적인 접근 방식을 살펴보겠습니다. 이 문서에서는 다음 내용을 다룹니다.

Interop 없이 Excel을 읽기 위한 C# .NET 라이브러리

Microsoft의 Excel Interop은 컴퓨터에 Excel이 설치되어 있어야 하므로 서버 측 애플리케이션에는 적합하지 않습니다. 대신 Spire.XLS와 같은 라이브러리는 Excel에 대한 종속성 없이 가볍고 고성능의 솔루션을 제공합니다.

Spire.XLS를 사용하는 이유

  • Excel 설치 필요 없음 – 독립적으로 작동합니다.
  • .NET Core 및 .NET Framework 지원 – 플랫폼 간 호환성.
  • Excel 파일 읽기/쓰기 – .xls, .xlsx 및 .xlsm을 지원합니다.
  • DataTable 및 데이터베이스로 가져오기 – ADO.NET과의 원활한 통합.

Spire.XLS 설치

시작하려면 NuGet 패키지 관리자를 통해 라이브러리를 설치하십시오.

Install-Package Spire.XLS

또는 공식 웹사이트에서 .NET용 Spire.XLS를 다운로드하고 DLL 파일을 수동으로 참조할 수 있습니다.

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

이 섹션에서는 Spire.XLS 라이브러리를 사용하여 C#에서 Excel 파일을 읽는 방법을 보여줍니다. 이 프로세스에는 파일 로드, 워크시트 액세스 및 프로그래밍 방식으로 셀 값 검색이 포함됩니다. 이는 데이터 추출 자동화, Excel 보고서 처리 또는 스프레드시트 데이터를 애플리케이션에 통합하는 데 유용합니다.

1단계. 필요한 네임스페이스 가져오기

Spire.XLS 기능을 활용하려면 해당 네임스페이스를 가져와야 합니다. 이를 통해 Excel 파일 작업에 필수적인 WorkbookWorksheet와 같은 클래스에 액세스할 수 있습니다.

  • C#
using Spire.Xls;

2단계. Excel 파일 로드

Excel 파일을 로드하려면 Workbook 개체를 만들고 LoadFromFile 메서드를 호출합니다. 이렇게 하면 파일이 메모리로 읽혀 추가 조작이 가능합니다.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("input.xlsx");

3단계. 특정 워크시트 가져오기

Excel 파일에는 여러 워크시트가 포함될 수 있습니다. Worksheets 컬렉션(0부터 시작)을 인덱싱하여 특정 시트에 액세스할 수 있습니다. 첫 번째 시트는 인덱스 0, 두 번째 시트는 1에 있는 식입니다.

  • C#
Worksheet sheet = wb.Worksheets[0]; //First sheet

4단계. 특정 셀의 값 검색

셀 값을 검색하려면 CellRange.Value 속성을 사용합니다. 행 및 열 인덱스(1부터 시작)를 지정하여 셀을 찾습니다. 이는 헤더나 개별 레코드와 같은 구조화된 데이터를 추출하는 데 유용합니다.

  • C#
CellRange cell = sheet.Range[1, 1]; // Row1, Column 1 (A1)
string value = cell.Value;

다음은 전체 워크시트에서 데이터를 읽어 콘솔에 인쇄하는 전체 예제입니다.

  • C#
using Spire.Xls;

namespace ReadExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an existing Excel file
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            // Get the cell range containing data
            CellRange locatedRange = sheet.AllocatedRange;

            // Iterate through the rows
            for (int i = 0; i < locatedRange.Rows.Length; i++)
            {
                // Iterate through the columns
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    // Get data of a specific cell
                    string cellValue = locatedRange[i + 1, j + 1].Value?.ToString() ?? "N/A";

                    // Align output with a width of 22
                    Console.Write($"{cellValue,-22}");
                }
                Console.WriteLine();
            }
        }
    }
}

결과:

read excel file in c#

Excel 데이터를 DataTable로 읽기

Excel 데이터를 DataTable로 내보내면 DataGridView와 같은 UI 컨트롤 또는 백엔드 데이터 처리와 원활하게 통합할 수 있습니다. Spire.XLS는 워크시트 데이터를 열 헤더와 데이터 유형을 유지하면서 구조화된 DataTable로 자동 변환하는 내장 ExportDataTable() 메서드를 사용하여 이 프로세스를 단순화합니다.

1단계. 필요한 네임스페이스 가져오기

필수 클래스에 액세스하려면 Spire.XLS 네임스페이스를 포함하십시오.

  • C#
using Spire.Xls;

2단계. 양식 및 버튼 클릭 이벤트 만들기

양식(예: Form1)을 만들고 Excel 파일을 읽기 위한 이벤트 처리기가 있는 버튼을 추가합니다.

  • C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Code will go here
    }
}

3단계. 통합 문서 로드

버튼 클릭 이벤트 내에서 Workbook 개체를 만들고 Excel 파일을 로드합니다.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

4단계. 데이터를 DataTable로 내보내기

인덱스로 특정 워크시트에 액세스하고 ExportDataTable 메서드를 사용하여 해당 데이터를 DataTable로 내보냅니다.

  • C#
DataTable dataTable = wb.Worksheets[0].ExportDataTable();

5단계. 데이터를 DataGridView에 바인딩

양식에 DataGridView 컨트롤이 있다고 가정하고 DataTable을 DataGridView에 바인딩하여 데이터를 표시합니다.

  • C#
dataGridView1.DataSource = dataTable;

다음은 Excel 파일에서 데이터를 읽어 DataTable에 넣고 Windows Forms DataGridView 컨트롤에 표시하는 전체 코드입니다.

  • C#
using Spire.Xls;
using System.Data;

namespace ReadExcelIntoDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an existing Excel file
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            // Export data from worksheet into a DataTable
            DataTable dataTable = sheet.ExportDataTable();

            // Bind DataTable to DataGridView
            dataGridView1.DataSource = dataTable;

            // Dispose resources
            wb.Dispose();
        }
    }
}

결과:

Excel 데이터가 MySQL 테이블에 표시됩니다.

Excel 데이터를 데이터베이스로 읽기

Excel 데이터를 데이터베이스와 통합하면 데이터 관리를 간소화할 수 있습니다. 아래에서는 Excel 파일을 읽고 그 내용을 MySQL 데이터베이스로 가져오는 과정을 안내합니다. 이 방법은 데이터 마이그레이션, 보고 또는 Excel 데이터를 구조화된 데이터베이스와 동기화하는 작업을 자동화하는 데 이상적입니다.

1단계. MySQL 데이터 라이브러리 설치

.NET 애플리케이션에서 MySQL 데이터베이스와 상호 작용하려면 MySql.Data 라이브러리를 설치해야 합니다. 이 NuGet 패키지는 MySQL 데이터베이스에 연결하고 조작하는 데 필요한 클래스와 메서드를 제공합니다.

  • C#
Install-Package MySql.Data

2단계. 필요한 네임스페이스 가져오기

Excel 파일 및 MySQL로 작업하기 전에 필요한 네임스페이스를 포함해야 합니다. Spire.XLS는 Excel 작업에 사용되고 MySql.Data.MySqlClient는 MySQL 데이터베이스 연결을 활성화합니다.

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

3단계. Excel에서 헤더 및 데이터 추출

다음 코드 조각은 Excel 파일에서 헤더와 데이터를 추출하는 방법을 보여줍니다. 헤더는 MySQL 열 이름 충돌을 피하기 위해 정리되고 데이터는 나중에 삽입할 수 있도록 구조화된 형식으로 저장됩니다.

  • C#
// Create a Workbook object
Workbook wb = new Workbook();

// Load an Excel document
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

// Get a specific sheet
Worksheet sheet = wb.Worksheets[0];

// Retrieve headers
List<string> headers = new List<string>();
for (int col = 1; col <= sheet.LastColumn; col++)
{
    string header = sheet.Range[1, col].Value?.ToString();
    // Removing spaces to avoid conflicts with MySQL column names
    string cleanHeader = header?.Replace(" ", "");
    headers.Add($"`{cleanHeader}`");
}

// Retrieve data
List<List<string>> data = new List<List<string>>();
for (int row = 2; row <= sheet.LastRow; row++) {
    List<string> record = new List<string>();
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
    }
    data.Add(record);
}

4단계. MySQL 데이터베이스에 연결

연결 문자열을 사용하여 MySQL 데이터베이스에 대한 연결이 설정됩니다. 여기에는 서버 세부 정보, 자격 증명 및 대상 데이터베이스 이름이 포함됩니다. using 문은 적절한 리소스 폐기를 보장합니다.

  • C#
string connectionString = "server=localhost;user=root;password=yourpassword;database=yourdatabase;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // Connection is established; perform database operations here
}

5단계. MySQL에서 동적으로 테이블 만들기

이 단계에서는 Excel 헤더와 일치하는 열이 있는 MySQL 테이블을 동적으로 생성합니다. 단순화를 위해 모든 열은 VARCHAR(255)로 설정되지만 요구 사항에 따라 데이터 유형을 조정할 수 있습니다.

  • C#
// Create a table with dynamic columns based on headers
List<string> columns = new List<string>();
foreach (string header in headers)
{
    // Assuming all header values are VARCHAR for simplicity; adjust types as needed
    columns.Add($"{header} VARCHAR(255)");
}

// Create a table in database
string columnsSql = string.Join(", ", columns);
string createTableQuery = $ @"
    CREATE TABLE IF NOT EXISTS my_table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        {columnsSql}
)";

// Execute the create table query
using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
{
    createCommand.ExecuteNonQuery();
}

6단계. 데이터로 테이블 채우기

추출된 Excel 데이터는 SQL 삽입을 방지하기 위해 매개변수화된 쿼리를 사용하여 MySQL 테이블에 삽입됩니다. Excel 파일의 각 행은 해당 데이터베이스 레코드에 매핑됩니다.

  • C#
// Prepare the SQL INSERT statement
string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

// Insert data into the table
foreach (List<string> record in data)
{
    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
    {
        for (int i = 0; i < record.Count; i++)
        {
            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
        }
        insertCommand.ExecuteNonQuery();
    }
}

다음은 Excel 파일에서 MySQL 테이블로 데이터를 가져오는 전체 코드입니다.

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

namespace ExcelToMySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an Excel document
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get a specific sheet
            Worksheet sheet = wb.Worksheets[0];

            // Retrieve headers
            List<string> headers = new List<string>();
            for (int col = 1; col <= sheet.LastColumn; col++)
            {
                string header = sheet.Range[1, col].Value?.ToString();
                // Removing spaces to avoid conflicts with MySQL column names
                string cleanHeader = header?.Replace(" ", "");
                headers.Add($"`{cleanHeader}`");
            }

            // Retrieve data
            List<List<string>> data = new List<List<string>>();
            for (int row = 2; row <= sheet.LastRow; row++)
            {
                List<string> record = new List<string>();
                for (int col = 1; col <= sheet.LastColumn; col++)
                {
                    record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
                }
                data.Add(record);
            }

            // Establish a connection to the MySQL database
            string connectionString = "server=localhost;user=root;password=admin;database=excel_db;";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                // Create a table with dynamic columns based on headers
                List<string> columns = new List<string>();
                foreach (string header in headers)
                {
                    // Assuming all header values are VARCHAR for simplicity; adjust types as needed
                    columns.Add($"{header} VARCHAR(255)");
                }

                // Create a table in database
                string columnsSql = string.Join(", ", columns);
                string createTableQuery = $ @"
                    CREATE TABLE IF NOT EXISTS my_table (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        {columnsSql}
                    )";

                // Execute the create table query
                using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
                {
                    createCommand.ExecuteNonQuery();
                }

                // Prepare the SQL INSERT statement
                string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
                string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

                // Insert data into the table
                foreach (List<string> record in data)
                {
                    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
                    {
                        for (int i = 0; i < record.Count; i++)
                        {
                            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
                        }
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }

            Console.WriteLine("데이터를 성공적으로 내보냈습니다!");
        }
    }
}

결과:

Excel 데이터가 MySQL 테이블에 표시됩니다.

결론

Spire.XLS와 같은 라이브러리 덕분에 C#에서 Excel 파일을 읽는 것이 그 어느 때보다 쉬워졌습니다. 이 가이드에서는 Excel 파일을 로드하고, 내용을 읽고, 데이터를 MySQL 데이터베이스로 가져오는 과정을 안내했습니다. 이러한 기술을 사용하면 애플리케이션의 데이터 처리 기능을 크게 향상시킬 수 있습니다.

자주 묻는 질문

Q1: 비밀번호로 보호된 Excel 파일을 읽을 수 있나요?

A: 예, Spire.XLS는 다음을 사용하여 암호화된 Excel 파일을 읽는 것을 지원합니다.

  • C#
wb.OpenPassword = "psd";
wb.LoadFromFile("file.xlsx");

Q2: 수식 자체가 아닌 수식 결과를 읽으려면 어떻게 해야 하나요?

A: 수식 결과를 검색하는 두 가지 옵션이 있습니다.

개별 셀의 경우:

CellRange.HasFormula를 사용하여 셀에 수식이 포함되어 있는지 확인하고 CellRange.FormulaValue로 값을 가져옵니다.

  • C#
CellRange cell = sheet.Range[1, 1];
if (cell.HasFormula)
{
    string result = cell.FormulaValue.ToString();
}

DataTable로 대량 내보내기의 경우:

계산된 값을 내보내려면 computedFormulaValue: true와 함께 Worksheet.ExportDataTable()을 사용하십시오.

  • C#
DataTable data = sheet.ExportDataTable(range, exportColumnNames: true, computedFormulaValue: true);

Q3: Excel 데이터를 DataTable로 어떻게 읽을 수 있나요?

A: Spire.XLS에서 제공하는 Worksheet.ExportDataTable() 메서드를 사용하십시오.

Q4: Excel 파일을 한 줄씩 어떻게 읽을 수 있나요?

A: 다음 코드를 참조하십시오.

  • C#
Workbook workbook = new Workbook();
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];

for (int row = 1; row <= sheet.LastRow; row++)
{
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        string cellValue = sheet.Range[row, col].Value?.ToString() ?? string.Empty;
        Console.WriteLine(cellValue);
    }
}

무료 라이선스 받기

평가 제한 없이 .NET용 Spire.XLS의 모든 기능을 경험하려면 30일 무료 평가판 라이선스를 요청할 수 있습니다.

참고 항목