0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でExcelファイルの作成し開いたままにする方法 - NPOIライブラリを使用

Posted at

はじめに

.NETでExcelファイルを操作するためには、NPOIというライブラリがよく使用されます。NPOIは、ExcelやWordなどのMicrosoft Officeファイルを読み書きできる強力なライブラリです。今回は、NPOIを使ってExcelファイルを作成し、それをユーザーのデスクトップに保存する方法になります。

全体の流れ

以下のコードは、NPOIを使用してExcelファイルを作成し、ユーザーデスクトップに保存する例です。

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // データを作成します。キーはシート名、値は各シートの行データとします。
        var excelData = new Dictionary<string, List<string>>();
        excelData.Add("Sheet1", new List<string> { "Item1", "Item2", "Item3" });
        excelData.Add("Sheet2", new List<string> { "Item4", "Item5", "Item6" });
        // Excelファイルを作成し保存します。結果をコンソールに表示します。
        string result = CreateAndSaveExcel(excelData);
        Console.WriteLine(result);
    }

    public static string CreateAndSaveExcel(Dictionary<string, List<string>> excelData)
    {
        // ワークブック(Excelファイル)を新規作成します。
        IWorkbook workbook = new XSSFWorkbook();
        // 入力データの各要素(シート)に対して処理を行います。
        foreach (var item in excelData)
        {
            // 新しいシートを作成します。シート名は入力データのキーから取得します。
            ISheet sheet = workbook.CreateSheet(item.Key);
            // シートの各行に対して処理を行います。
            for (int i = 0; i < item.Value.Count; i++)
            {
                // 新しい行を作成します。
                IRow row = sheet.CreateRow(i);     
                // 行の最初のセルを作成し、値を設定します。
                ICell cell = row.CreateCell(0);
                cell.SetCellValue(item.Value[i]);
            }
        }
        // 保存するExcelファイルのパスを指定します。
        string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ExcelOutput.xlsx");

        try
        {
            // FileStreamを使用してExcelファイルを書き込みモードで開きます。
            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                // ワークブックの内容をExcelファイルに書き込みます。
                workbook.Write(fs);
            }
        }
        catch (Exception)
        {
            // 何らかのエラーが発生した場合は失敗メッセージを返します。
            return "Excel export failed.";
        }
        // Excelファイルを開きます。
        Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true });
        // Excelファイルの作成と保存が成功した場合は成功メッセージを返します。
        return "Excel export completed.";
    }
}

データの作成

まず、Excelに書き込むためのデータを作成します。このコードでは、Dictionary<string, List<string>>型の変数dataForExcelを使用しています。ここで、Dictionaryはキーと値のペアを格納するコレクションです。

var dataForExcel = new Dictionary<string, List<string>>();
dataForExcel.Add("Sheet1", new List<string> { "Item1", "Item2", "Item3" });
dataForExcel.Add("Sheet2", new List<string> { "Item4", "Item5", "Item6" });

このコードでは、Sheet1Sheet2という2つのシートを作成し、そのシートにそれぞれ3つのデータ(Item1, Item2, Item3Item4, Item5, Item6)を追加しています。

Excelファイルの作成

次に、新しいExcelワークブックを作成します。NPOIライブラリを使用してExcelワークブックを作成するためには、XSSFWorkbookクラスを使用します。

IWorkbook workbook = new XSSFWorkbook();

そして、作成したデータを使ってExcelのシートとその中のデータを作成します。CreateSheetメソッドを使用してシートを作成し、CreateRowメソッドとCreateCellメソッドを使用して各行とセルを作成します。

foreach (var item in dataForExcel)
{
    ISheet sheet = workbook.CreateSheet(item.Key);
    for (int i = 0; i < item.Value.Count; i++)
    {
        IRow row = sheet.CreateRow(i);
        ICell cell = row.CreateCell(0);
        cell.SetCellValue(item.Value[i]);
    }
}

Excelファイルの保存

最後に、作成したExcelファイルをユーザーのデスクトップに保存します。これを行うためには、FileStreamクラスを使用します。

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ExcelOutput.xlsx");

ここでは、Environment.GetFolderPath(Environment.SpecialFolder.Desktop)を使用してデスクトップのパスを取得し、Path.Combineメソッドを使用してそのパスとファイル名を結合しています。

次に、FileStreamを使用してファイルを作成し、ワークブックの内容を書き込みます。

using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
    workbook.Write(fs);
}

最後に、作成したExcelファイルを開きます。これを行うためには、Process.Startメソッドを使用します。

Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true });

以上が、NPOIを使用してExcelファイルを作成し、それをユーザーのデスクトップに保存する詳細な解説です。このコードを実行することで、指定したデータを含むExcelファイルがデスクトップに作成され、自動的にそのファイルが開きます。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?