C#アプリケーションでExcelファイルをプログラム的に開くことは一般的な要件ですが、多くの開発者は従来のアプローチの限界に苦労しています。このガイドでは、Microsoft Excelのインストールを必要としない無料のオープンソースライブラリであるOpenize.OpenXML SDKを使用して、C#でExcelファイルを開く方法を説明します。

Excel をインストールせずに C# で Excel ファイルを開く方法

従来の方法の問題点

ほとんどの開発者は Microsoft.Office.Interop.Excel から始めますが、このアプローチには重大な制限があります。

  • ❌ すべてのマシンにExcelのインストールが必要
  • ❌ パフォーマンスの低下とメモリリーク
  • ❌ サーバーアプリケーションには適していません
  • ❌ Webアプリケーションにおけるスレッドの問題
  • ❌ ライセンス費用が高額

解決策: Openize.OpenXML SDK

Openize.OpenXML SDK はこれらの問題を解決します。

  • ✅ Excelのインストールは不要
  • ✅ 高性能でスレッドセーフ
  • ✅ Webアプリケーションやサーバーに最適
  • ✅ オープンソースで完全に無料
  • ✅ シンプルで直感的なAPI

インストール

Openize.OpenXML SDK をプロジェクトに追加します。

<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />

基本的な例: Excel ファイルを開いて読み込む

using Openize.Cells;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // Open existing Excel file
            using (var workbook = new Workbook("sample.xlsx"))
            {
                // Get the first worksheet
                var worksheet = workbook.Worksheets[0];
                
                Console.WriteLine($"Worksheet Name: {worksheet.Name}");
                Console.WriteLine($"Total Rows: {worksheet.GetRowCount()}");
                Console.WriteLine($"Total Columns: {worksheet.GetColumnCount()}");
                
                // Read specific cell values
                string cellA1 = worksheet.Cells["A1"].GetValue();
                string cellB1 = worksheet.Cells["B1"].GetValue();
                
                Console.WriteLine($"Cell A1: {cellA1}");
                Console.WriteLine($"Cell B1: {cellB1}");
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Excel file not found!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

開く前に Excel ファイルが存在するかどうかを確認する

using Openize.Cells;
using System.IO;

public class ExcelFileHandler
{
    public static void OpenExcelSafely(string filePath)
    {
        // Check if file exists
        if (!File.Exists(filePath))
        {
            Console.WriteLine($"File not found: {filePath}");
            return;
        }
        
        try
        {
            using (var workbook = new Workbook(filePath))
            {
                var worksheet = workbook.Worksheets[0];
                Console.WriteLine($"Successfully opened: {filePath}");
                Console.WriteLine($"First cell value: {worksheet.Cells["A1"].GetValue()}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed to open Excel file: {ex.Message}");
        }
    }
}

複数のワークシートを読み取る

using Openize.Cells;

public class MultiSheetReader
{
    public static void ReadAllWorksheets(string filePath)
    {
        using (var workbook = new Workbook(filePath))
        {
            Console.WriteLine($"Total worksheets: {workbook.Worksheets.Count}");
            
            foreach (var worksheet in workbook.Worksheets)
            {
                Console.WriteLine($"\nWorksheet: {worksheet.Name}");
                Console.WriteLine($"Rows: {worksheet.GetRowCount()}");
                Console.WriteLine($"Columns: {worksheet.GetColumnCount()}");
                
                // Read first few cells
                for (int row = 1; row <= 3; row++)
                {
                    for (int col = 1; col <= 3; col++)
                    {
                        string cellRef = GetCellReference(row, col);
                        string value = worksheet.Cells[cellRef].GetValue();
                        Console.Write($"{value}\t");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
    
    static string GetCellReference(int row, int col)
    {
        return $"{GetColumnLetter(col)}{row}";
    }
    
    static string GetColumnLetter(int columnNumber)
    {
        string columnLetter = string.Empty;
        while (columnNumber > 0)
        {
            columnNumber--;
            columnLetter = (char)('A' + columnNumber % 26) + columnLetter;
            columnNumber /= 26;
        }
        return columnLetter;
    }
}

結論

Openize.OpenXML SDKは、Excel Interopの複雑な処理を必要とせず、C#でExcelファイルを開くための信頼性と効率性を提供します。デスクトップアプリケーション、Webサービス、サーバーサイド処理に最適です。 主なメリット:

  • Excelのインストールは不要
  • 高性能
  • Webアプリケーション用のスレッドセーフ
  • オープンソースで無料
  • 使いやすいAPI 次のプロジェクトで試してみて、違いを体験してください。