0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C# で SQL データを Excel にエクスポート

Posted at

業務システムや社内ツールの開発では、SQL データベースに保存されているデータを Excel 形式で出力し、分析・報告・共有する場面がよくあります。このとき、DataTable を中間データ構造として利用し、Excel ファイル(.xlsx)に変換するのが一般的です。

この記事では、以下の手順で実装方法を紹介します:

  • SQL Server データベースから DataTable にデータを読み込む
  • C# で DataTable を Excel ファイルに書き込む
  • 書き出した Excel ファイルの書式を整えて見やすくする

この記事の例では Free Spire.XLS for .NET を使用します。NuGet からインストール可能です:


Install-Package FreeSpire.XLS


SQL データベースから DataTable を取得する

まずは、SQL Server データベースに格納された従業員情報を取得します。以下の例では、Employees というテーブルを使用します。

CREATE TABLE StaffMembers (
    StaffId INT PRIMARY KEY IDENTITY,
    FullName NVARCHAR(100) NOT NULL,
    Division NVARCHAR(50) NOT NULL,
    JobTitle NVARCHAR(50),
    StartDate DATE NOT NULL,
    MonthlyPay DECIMAL(10, 2) NOT NULL,
    IsPermanent BIT NOT NULL
);

INSERT INTO StaffMembers (FullName, Division, JobTitle, StartDate, MonthlyPay, IsPermanent) VALUES
('Ethan Williams', 'Operations', 'Operations Supervisor', '2017-03-12', 6100.00, 1),
('Sophia Martinez', 'IT', 'System Administrator', '2019-07-22', 6900.40, 1),
('Liam Brown', 'Finance', 'Financial Analyst', '2021-04-18', 5750.25, 0),
('Olivia Davis', 'Sales', 'Sales Executive', '2022-09-05', 5300.00, 1);

C# で DataTable にデータを読み込むコードは以下の通りです。

using System.Data;
using Microsoft.Data.SqlClient;

string connectionString = @"Data Source=YourServer\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True";

DataTable dataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    string query = "SELECT Id, Name, Department, Position, HireDate, Salary, IsFullTime FROM Employees";
    using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
    {
        adapter.Fill(dataTable);
    }
}

これで dataTable に従業員データが格納されました。


DataTable を Excel ファイルにエクスポートする

次に、取得した DataTable を Excel ファイルとして出力します。Spire.XLS の Workbook クラスと Worksheet クラスを利用して操作します。

using Spire.Xls;

// 新しいブックを作成
Workbook workbook = new Workbook();
workbook.Worksheets.Clear();
Worksheet sheet = workbook.Worksheets.Add("Employees Data");

// A1 セルから DataTable を挿入(true = 列名を含める)
sheet.InsertDataTable(dataTable, true, 1, 1);

// ファイルとして保存
workbook.SaveToFile("Employees.xlsx", ExcelVersion.Version2016);

このコードを実行すると、Employees.xlsx ファイルが作成され、SQL データベースの内容が Excel に出力されます。
C#を使用してデータベースをExcelにエクスポートする


Excel の書式を設定して見やすくする

生のデータを出力するだけでは、見た目がシンプルすぎて可読性に欠けることがあります。そこで、表頭やデータ行、列幅などを整えます。

using System.Drawing;

// 表頭のスタイル設定
CellRange headerRow = sheet.Rows[0];
headerRow.Style.Font.IsBold = true;
headerRow.Style.Font.Size = 14;
headerRow.Style.Font.FontName = "Calibri";
headerRow.Style.Color = Color.LightSteelBlue;
headerRow.Style.HorizontalAlignment = HorizontalAlignType.Center;

// データ行のスタイル設定
for (int i = 1; i < sheet.Rows.Count(); i++)
{
    CellRange dataRow = sheet.Rows[i];
    dataRow.Style.Font.Size = 12;
    dataRow.Style.Font.FontName = "Segoe UI";
    dataRow.Style.HorizontalAlignment = HorizontalAlignType.Left;
}

// 日付列の書式設定
CellRange dateColumn = sheet.Range[2, 5, sheet.Rows.Count(), 5];
dateColumn.Style.NumberFormat = "yyyy-mm-dd";

// 給与列の数値書式設定
CellRange salaryColumn = sheet.Range[2, 6, sheet.Rows.Count(), 6];
salaryColumn.Style.NumberFormat = "#,##0.00";

// 枠線を設定
sheet.AllocatedRange.BorderAround(LineStyleType.Medium, Color.Black);
sheet.AllocatedRange.BorderInside(LineStyleType.Thin, Color.Gray);

// 列幅を自動調整
sheet.AllocatedRange.AutoFitColumns();

// 書式を反映したファイルを保存
workbook.SaveToFile("Employees_Styled.xlsx", ExcelVersion.Version2016);

上記の設定により:

  • 表頭は太字・背景色付きで中央寄せ
  • 日付は yyyy-mm-dd 形式
  • 給与はカンマ区切り・小数点以下 2 桁表示
  • 枠線付きで見やすい表に
  • 列幅が自動調整されるため、内容が見切れない

エクスポートされたExcelファイル:
C#を使用してデータベースをフォーマットされたExcelファイルにエクスポートする


まとめ

この記事では、

  1. SQL Server データベースから DataTable にデータを読み込む
  2. Spire.XLS を使って DataTable を Excel にエクスポートする
  3. 書式を整えて見やすくする

という流れを紹介しました。

この方法は、社内業務報告書、データ分析用の出力、管理システムのエクスポート機能 など、幅広い場面で活用できます。

さらに、数式、グラフ、条件付き書式 などの高度な Excel 機能も Spire.XLS で実現可能です。詳細は Spire.XLS の公式ドキュメント をご参照ください。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?