フッターコンテンツにスキップ
IRONXLの使用
C#でExcelデータを読み取り、データベーステーブルに挿入する方法 | IronXL

C#でExcelデータを読み込み、データベースに挿入する

This article will explore how to use IronXL, a C# Excel Library, to read data from an Excel file and insert it into a database table.

1. IronXL

IronXL is a powerful software library designed for .NET developers, providing them with an easy-to-use API to read, write, and manipulate Excel files in their .NET applications. It offers a comprehensive set of features for creating, editing, and exporting Excel spreadsheets, all without requiring Microsoft Office or Excel to be installed on the target machine. With support for a wide range of file formats, including XLS, XLSX, CSV, TSV, and more, this library makes it easy for developers to create Excel-based applications that can be deployed anywhere. IronXL also offers advanced features like chart creation, data visualization, and data analysis to streamline the development process for small to large-scale projects.

2. 事前準備

Before you can use the IronXL library to write to a database from an Excel file, you must fulfill certain prerequisites. これには以下が含まれます:

  • Having Visual Studio installed on your computer to create a C# project.
  • Ensuring that ASP.NET is also installed on your system before creating a C# project.
  • Installing the IronXL library on your system to export data. Visual StudioのNuGetパッケージマネージャーからIronXL NuGetパッケージをダウンロードすることで入手できます。
  • Having SQL installed in Visual Studio.

3. Visual Studioで新しいプロジェクトを作成する

Before you can utilize the IronXL library to perform Excel-related operations, you need to create a .NET project in Visual Studio. While any version of Visual Studio is compatible, it is recommended to use the latest version available. You can choose from various project templates such as Windows Forms and ASP.NET, based on your project requirements. For this tutorial, the Console Application project template is recommended to demonstrate how to work with IronXL.

How to Read Excel Data and Insert to Database Table in C#, Figure 1: Create a new project window Create a new project

プロジェクトタイプを選択した後、プロジェクトに名前を付け、その場所を選択する必要があります。 また、プロジェクトのために好みのフレームワーク(例:.NET Core 6)を指定することもできます。

How to Read Excel Data and Insert to Database Table in C#, Figure 2: Project configuration プロジェクト構成

After the new project is created, you can access the program.cs file where you can write code and execute the application.

How to Read Excel Data and Insert to Database Table in C#, Figure 3: Project with code open コードオープンのプロジェクト

Now the Visual Studio project is created, let's install IronXL.

4. IronXLのインストール

The IronXL library can be downloaded and installed in different ways, but for this article, two simplest methods are covered:

  • Using NuGet packages in Visual Studio.
  • Visual Studioコマンドラインを使用します。

4.1 Visual Studioを使用する

IronXLライブラリをインストールする最初の方法は、Visual StudioのNuGetパッケージ マネージャーを使用することです。 NuGetパッケージマネージャを開き、参照タブでIronXLを検索してください。 検索結果でIronXLを見つけたら、それを選択してインストールを進めます。 インストールが完了したら、プロジェクトでIronXLライブラリを使用し始めることができます。

The following screenshot shows how to open the NuGet Package Manager in Visual Studio.

How to Read Excel Data and Insert to Database Table in C#, Figure 4: NuGet Package Manager NuGetパッケージマネージャー

The following screenshot shows IronXL in the search results:

How to Read Excel Data and Insert to Database Table in C#, Figure 5: IronXL search result IronXL検索結果

4.2 Visual Studioコマンドラインを使用する

多くの開発者はコマンドラインインターフェースを使用してパッケージをインストールすることを好みます。 コマンドラインを使用してIronXLをインストールするには、次の手順を実行します:

  • In Visual Studio, go to Tools > NuGetパッケージマネージャー > Package Manager Console.
  • パッケージマネージャコンソールタブで次の行を入力してください:

    Install-Package IronXL
    Install-Package IronXL
    SHELL

The package will be downloaded and installed into the current project.

How to Read Excel Data and Insert to Database Table in C#, Figure 6: Installing via command line コマンドラインによるインストール

5. Installing and Configuring the SQL Server Database

To install and integrate the SQL server database table with your C# project, first, go to the NuGet Package Manager, search for System.Data.SqlClient, and install it.

How to Read Excel Data and Insert to Database Table in C#, Figure 7: Search and install SqlClient in NuGet Package Manager UI Search and install SqlClient in NuGet Package Manager UI

Once installed, go to the project menu and click on "Add New Item".

How to Read Excel Data and Insert to Database Table in C#, Figure 8: Add New Item Add New Item

新しいウィンドウが表示されます。 Select data from the side menu and then click on Service-Based Database from the list. Write an appropriate name for the database and click the Add button.

How to Read Excel Data and Insert to Database Table in C#, Figure 9: Select Service-based Database Select Service-based Database

Then, in the Solution Explorer, right-click on the newly created database and select "Open". This will open a new sidebar.

How to Read Excel Data and Insert to Database Table in C#, Figure 10: Right-click and select Open Right-click and select Open

In the new sidebar, click on your database and go to its properties. From there, copy the connection string.

How to Read Excel Data and Insert to Database Table in C#, Figure 11: Right-click and select Properties Right-click and select Properties

How to Read Excel Data and Insert to Database Table in C#, Figure 12: Handle Connection String Handle Connection String

After copying the connection preferences, click on your database instance to open a new list. Right-click on the table folder and select "Add New Table".

How to Read Excel Data and Insert to Database Table in C#, Figure 13: Add New Table Add New Table

To create a new table in the database, follow these steps:

  1. Open a new data table design page.
  2. Add the following SQL Query, which will create a new table with three columns: Id, Name, and Number.
  3. Click on the "Update" button at the top of the page.
  4. The newly generated table will be added to the database.
CREATE TABLE [dbo].[Table]
(
  [Id] INT NOT NULL PRIMARY KEY,
  [Name] VARCHAR(100) NOT NULL,
  [Number] INT
)

Now that the SQL environment is set up, let's create some sample data to fill this database from Excel data.

How to Read Excel Data and Insert to Database Table in C#, Figure 14: Excel file data Excel file data

6. Import Excel File Data and Export to a Database using IronXL

With IronXL, developers can automate the process of transferring data between Excel files and databases, which can save a significant amount of time and effort. By utilizing IronXL, developers can streamline their workflow and eliminate the need for manual data entry, ensuring that the data is accurate and up-to-date.

Once the SQL server is set up and the connection string is copied, just paste the connection string into the code below, link your Excel file with the code, and change the SQL query if needed. Then simply run the code and the data will be exported to the database table.

using IronXL; // Import the IronXL library
using System.Data; // Import data handling library
using System.Data.SqlClient; // Import SQL Client library for SQL database operations

// Load the Excel workbook
WorkBook workBook = WorkBook.Load("book.xlsx");

// Convert the workbook into a DataSet
DataSet dataSet = workBook.ToDataSet();

// Define the SQL query to select data from the table
string sql = "SELECT * FROM [dbo].[Table]";

// Connection string for the SQL Server
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\USERS\BUTTW\SOURCE\REPOS\CREATE PDF\CREATE PDF\DATABASE1.MDF;Integrated Security=True"; 

// Open a connection to the SQL Server using the connection string
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open(); // Open connection
    // Use SqlDataAdapter to update SQL table with DataSet from Excel file
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    adapter.Update(dataSet);
}
using IronXL; // Import the IronXL library
using System.Data; // Import data handling library
using System.Data.SqlClient; // Import SQL Client library for SQL database operations

// Load the Excel workbook
WorkBook workBook = WorkBook.Load("book.xlsx");

// Convert the workbook into a DataSet
DataSet dataSet = workBook.ToDataSet();

// Define the SQL query to select data from the table
string sql = "SELECT * FROM [dbo].[Table]";

// Connection string for the SQL Server
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\USERS\BUTTW\SOURCE\REPOS\CREATE PDF\CREATE PDF\DATABASE1.MDF;Integrated Security=True"; 

// Open a connection to the SQL Server using the connection string
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open(); // Open connection
    // Use SqlDataAdapter to update SQL table with DataSet from Excel file
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    adapter.Update(dataSet);
}
Imports IronXL ' Import the IronXL library
Imports System.Data ' Import data handling library
Imports System.Data.SqlClient ' Import SQL Client library for SQL database operations

' Load the Excel workbook
Private workBook As WorkBook = WorkBook.Load("book.xlsx")

' Convert the workbook into a DataSet
Private dataSet As DataSet = workBook.ToDataSet()

' Define the SQL query to select data from the table
Private sql As String = "SELECT * FROM [dbo].[Table]"

' Connection string for the SQL Server
Private connectionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\USERS\BUTTW\SOURCE\REPOS\CREATE PDF\CREATE PDF\DATABASE1.MDF;Integrated Security=True"

' Open a connection to the SQL Server using the connection string
Using connection As New SqlConnection(connectionString)
	connection.Open() ' Open connection
	' Use SqlDataAdapter to update SQL table with DataSet from Excel file
	Dim adapter As New SqlDataAdapter(sql, connection)
	adapter.Update(dataSet)
End Using
$vbLabelText   $csharpLabel

To check if the data has been successfully exported to the database, right-click on the table directory again and click on "New Query." A new page will open, select your database from the top bar and run the appropriate SQL query to retrieve the data.

SELECT * FROM [dbo].[Table]

Press the green button, and the result will be displayed in a second.

How to Read Excel Data and Insert to Database Table in C#, Figure 15: Database data Database data

This is how you can write data imported from a Microsoft Excel file to a database.

7. 結論

Working with Excel spreadsheets is a common task in many applications, and inserting data from an Excel sheet into a database table can streamline data management processes. One way to achieve this task in C# is by using libraries that allow reading and manipulating Excel files, such as IronXL. By utilizing this library, developers can easily extract data from an Excel sheet and insert it into a database table, simplifying the data management process and reducing the chances of errors. This article covers the steps involved in adding data from an Excel file to a SQL Server table in a SQL Server database using the IronXL library. It also provides a brief introduction to the IronXL library, discusses the prerequisites needed to insert data, and describes how to create a new project in Visual Studio, install IronXL, and configure an SQL Server database. Please visit the following tutorial to learn how to read Excel files in C#.

Additionally, IronXL also offers advanced features including support for cell formatting such as text alignment, font size, color, freeze panel, adding formulas, applying conditional formatting, and encryption with a password.

Users can also benefit from Iron Suite, a collection of software development tools that includes IronPDF, IronOCR, IronXL, IronBarcode, and IronWebscraper.

よくある質問

C#でExcelファイルからデータを読み取るにはどうすればいいですか?

IronXLを使用して、C#でExcelファイルからデータを読み取ることができます。IronXLはExcelファイルを開いて読み取るメソッドを提供し、プログラムでデータにアクセスして操作することができます。

C#でExcelデータをSQLデータベースに挿入する手順は何ですか?

C#を使用してExcelデータをSQLデータベースに挿入するには、まずIronXLを使用してデータを読み取り、DataSetに変換します。その後、SqlDataAdapterを使用してデータベーステーブルをDataSetで更新します。

Excelデータをインポートするための新しいデータベーステーブルを作成するにはどうすればよいですか?

SQLクエリ(例: CREATE TABLE [dbo].[Table] ( [Id] INT NOT NULL PRIMARY KEY, [Name] VARCHAR(100) NOT NULL, [Number] INT ))を実行して、テーブル構造を定義することで新しいデータベーステーブルを作成できます。

C#プロジェクトでIronXLを使用するための前提条件は何ですか?

前提条件には、Visual Studioがインストールされていること、NuGetパッケージマネージャーからのIronXLライブラリがあること、およびVisual Studio環境でSQL Serverが構成されていることが含まれます。

Excelデータがデータベースに正常に挿入されたか確認する方法は?

SQL Serverデータベースのデータエントリを取得し、レビューするためにSELECT * FROM [dbo].[Table]のようなSQLクエリを実行することで、データ挿入を確認できます。

IronXLが提供する高度な機能は何がありますか?

IronXLは、グラフ作成、データ視覚化、セルの書式設定、パネルの固定、数式の追加、条件付き書式、およびパスワードによる暗号化などの高度な機能を提供します。

Visual StudioプロジェクトにIronXLをインストールするにはどうすればよいですか?

IronXLをVisual Studioプロジェクトにインストールするには、NuGetパッケージマネージャーを使用してIronXLを検索し、インストールするか、Visual StudioのコマンドラインでInstall-Package IronXLを実行してください。

なぜExcelとSQLデータベースの間でデータ転送にIronXLを使用する必要があるのですか?

IronXLを使用してExcelとSQLデータベース間でデータ転送を行うと、プロセスが自動化され、データの正確性が確保され、最新情報を維持したまま時間を節約できます。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。