Sheet1シートがあるファイルを開き、
シート名で参照する方法と、シート番号で参照する方法
また、存在しないシート名を指定するとどうなるか確認

ExcelVBA

シート番号と名前でアクセスする方法
シート番号は1から始まることに注意
存在しない場合はエラーとなるので例外の対応を行っておく

Sub Sample()
    Dim BookObj     As Workbook
    Dim FilePath    As String
    Dim SheetObj    As Worksheet
    
    'ファイルパス作成
    FilePath = ThisWorkbook.Path & "\sample.xlsx"
    
    'ブックを開く
    Set BookObj = Workbooks.Open(FilePath)
    
    'シート番号で参照
    Set SheetObj = BookObj.Sheets(1)
    Debug.Print "シート番号で参照:" & SheetObj.Name
    
    '名前で参照
    Set SheetObj = BookObj.Sheets("Sheet1")
    Debug.Print "シート名で参照:" & SheetObj.Name
    
    On Error Resume Next
    '存在しない名前を指定して参照 => 例外が発生する
    Set SheetObj = BookObj.Sheets("AAA")
    
    If ERR.Number <> 0 Then
        Debug.Print ERR.Description 'インデックスが有効範囲にありません。
    End If
    
    On Error GoTo 0 'On Error Resume Next解除
    
    '保存せず閉じる
    BookObj.Close (False)
    
    Set BookObj = Nothing
    Set SheetObj = Nothing
End Sub

Excel(COM)

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System;
using System.Data;

namespace SampleCode; // C#10~

internal class SampleExcel
{
    static void Main(string[] args)
    {
        Excel.Application? application = null;
        Excel.Workbooks? workbooks = null;
        Excel.Workbook? workbook = null;
        Excel.Sheets? worksheets = null;
        Excel.Worksheet? worksheet = null;
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // Excelを開く
            application = new Excel.Application();
            application.Visible = true;

            // ブックを開く
            workbooks = application.Workbooks;
            workbook = workbooks.Open(filePath);

            // シートを取得
            worksheets = workbook.Sheets;

            // シート番号で参照
            worksheet = worksheets[1];
            Console.WriteLine($"シート番号で参照:{worksheet.Name}");
            CleanUpComObject(ref worksheet);

            // シート名で参照
            worksheet = worksheets["Sheet1"];
            Console.WriteLine($"シート名で参照:{worksheet.Name}");
            CleanUpComObject(ref worksheet);

            try
            {
                // 存在しない名前を指定して参照 => 例外が発生する
                worksheet = worksheets["AAA"];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message); // インデックスが無効です。 (0x8002000B (DISP_E_BADINDEX))
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            CleanUpComObject(ref worksheet);
            CleanUpComObject(ref worksheets);
            CleanUpComObject(ref workbook, true, false);
            CleanUpComObject(ref workbooks);
            CleanUpComObject(ref application);

            // RCW強制解放(残留プロセス対策)
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

    static void CleanUpComObject<T>(ref T comObject, bool shouldClose = true, bool saveChanges = false)
    {
        // フラグによってWorkbookはClose / ApplicationはQuitする
        if (shouldClose && comObject != null)
        {
            // 型をチェックする
            if (comObject is Microsoft.Office.Interop.Excel.Workbook workbook)
            {
                // Workbookの場合
                workbook.Close(saveChanges);
            }
            else if (comObject is Microsoft.Office.Interop.Excel.Application application)
            {
                // Applicationの場合
                application.Quit();
            }
        }

        // Objectを解放
        if (comObject != null && Marshal.IsComObject(comObject))
        {
            Marshal.ReleaseComObject(comObject);
            comObject = default!;
        }
    }
}

補足:Microsoft.Office.Interop.Excel でオブジェクトの解放について

ClosedXML

using ClosedXML.Excel;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleClosedXML
{
    static void Main(string[] args)
    {
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // ブックを開く、読み書きモード、共有なし(排他)
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var workbook = new XLWorkbook(fileStream))
            {
                // シート番号で参照
                var sheet = workbook.Worksheet(1);
                Console.WriteLine($"シート番号で参照:{sheet.Name}");

                // シート名で参照
                sheet = workbook.Worksheet("Sheet1");
                Console.WriteLine($"シート名で参照:{sheet.Name}");

                // 存在しない名前を指定して参照 => 例外発生する
                try
                {
                    sheet = workbook.Worksheet("AAA"); // There isn't a worksheet named 'AAA'.
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                // TryGetWorksheetを使うのも一つの手
                IXLWorksheet? worksheet = null;
                if (!workbook.TryGetWorksheet("AAA", out worksheet))
                {
                    Console.WriteLine("AAAシートないよ");
                }

                // 存在しないシートについては、Containsでtrue/falseを返してくれる
                if (!workbook.Worksheets.Contains("AAA"))
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

EPPlus

using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleEPPlus
{
    static void Main(string[] args)
    {
        // Ver8.0のソースです
        // 非商用個人利用の場合 名前を設定
        ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // ブックを開く、読み書きモード、共有なし(排他)
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var package = new ExcelPackage(stream))
            {
                // シート番号で参照(シート番号は0から)
                var sheet = package.Workbook.Worksheets[0];
                Console.WriteLine($"シート番号で参照:{sheet.Name}");

                // シート名で参照
                sheet = package.Workbook.Worksheets["Sheet1"];
                Console.WriteLine($"シート名で参照:{sheet.Name}");

                // 存在しない名前を指定して参照 => nullを返す
                sheet = package.Workbook.Worksheets["AAA"];
                if(sheet == null)
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

ExcelDataReader

using ExcelDataReader;
using System;
using System.Data;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleExcelDataReader
{
    static void Main(string[] args)
    {
        // デフォルトでは、エンコード(CP1252)がサポートされておらずエラーになるのでこれが必要
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // ファイル開く、読み書きモード、共有なし(排他)
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (var reader = ExcelReaderFactory.CreateReader(fileStream))
            {
                // DataSetに変換(シート情報を取得)
                var result = reader.AsDataSet();

                // シート番号で参照(シート番号は0から)
                var sheet = result.Tables[0];
                Console.WriteLine($"シート番号で参照:{sheet.TableName}");

                // シート名で参照
                sheet = result.Tables["Sheet1"];
                Console.WriteLine($"シート名で参照:{sheet.TableName}");

                // 存在しない名前を指定して参照 => nullを返す
                sheet = result.Tables["AAA"];
                if (sheet == null)
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

NPOI

□xls

using NPOI.HSSF.UserModel;
using System;
using System.IO;
using System.Reflection;


namespace SampleCode; // C#10~

internal class SampleNPOI_xls
{
    static void Main(string[] args)
    {
        var filePath = "";

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            filePath = Path.Combine(folderPath, "sample.xls");

            // ブックを開く、読み書きモード、共有なし(排他)
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var workbook = new HSSFWorkbook(fileStream))
            {
                // シート番号で参照(シート番号は0から)
                var sheet = workbook.GetSheetAt(0);
                Console.WriteLine($"シート番号で参照:{sheet.SheetName}");

                // シート名で参照
                sheet = workbook.GetSheet("Sheet1");
                Console.WriteLine($"シート名で参照:{sheet.SheetName}");

                // 存在しない名前を指定して参照 => nullを返す
                sheet = workbook.GetSheet("AAA");
                if (sheet == null)
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

□xlsx

using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleNPOI_xlsx
{
    static void Main(string[] args)
    {
        var filePath = "";

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            filePath = Path.Combine(folderPath, "sample.xlsx");

            // ブックを開く、読み書きモード、共有なし(排他)
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var workbook = new XSSFWorkbook(fileStream))
            {
                // シート番号で参照(シート番号は0から)
                var sheet = workbook.GetSheetAt(0);
                Console.WriteLine($"シート番号で参照:{sheet.SheetName}");

                // シート名で参照
                sheet = workbook.GetSheet("Sheet1");
                Console.WriteLine($"シート名で参照:{sheet.SheetName}");

                // 存在しない名前を指定して参照 => nullを返す
                sheet = workbook.GetSheet("AAA");
                if (sheet == null)
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

□xlsもxlsxも扱う場合
Program.cs

using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleNPOI
{
    static void Main(string[] args)
    {
        var filePath = "";

        try
        {   // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            filePath = Path.Combine(folderPath, "sample.xlsx");

            var extension = Path.GetExtension(filePath);

            // ブックを開く、読み書きモード、共有なし(排他)
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var workbook = WorkbookFactory.Create(fileStream, extension))
            {
                // シート番号で参照(シート番号は0から)
                var sheet = workbook.GetSheetAt(0);
                Console.WriteLine($"シート番号で参照:{sheet.SheetName}");

                // シート名で参照
                sheet = workbook.GetSheet("Sheet1");
                Console.WriteLine($"シート名で参照:{sheet.SheetName}");

                // 存在しない名前を指定して参照 => nullを返す
                sheet = workbook.GetSheet("AAA");
                if (sheet == null)
                {
                    Console.WriteLine("AAAシートないよ");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

WorkbookFactory.cs

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;

namespace SampleCode
{
    public class WorkbookFactory
    {
        public static IWorkbook Create(Stream stream, string extension)
        {
            extension = extension.ToLower();

            return extension switch
            {
                ".xls" => new HSSFWorkbook(stream),
                ".xlsx" => new XSSFWorkbook(stream),
                _ => throw new NotSupportedException("対象外の拡張子です")
            };
        }

        public static IWorkbook Create(string extension)
        {
            extension = extension.ToLower();

            return extension switch
            {
                ".xls" => new HSSFWorkbook(),
                ".xlsx" => new XSSFWorkbook(),
                _ => throw new NotSupportedException("対象外の拡張子です")
            };
        }
    }
}
投稿日時: 2025-05-24 16:47:24
更新日時: 2025-05-27 14:33:27

ExcelVBA

Sub Sample()
    Dim BookObj         As Workbook
    Dim c               As Long
    Dim FilePath        As String
    Dim r               As Long
    Dim SheetObj        As Worksheet
        
    'ファイルパス作成
    FilePath = ThisWorkbook.Path & "\sample.xlsx"
    
    'ブックを開く
    Set BookObj = Workbooks.Open(FilePath)
    
    'シート取得
    Set SheetObj = BookObj.Sheets("Sheet1")
    
    SheetObj.Range("A1").Value = 1
    SheetObj.Range("A2").Value = 1.1
    SheetObj.Range("A3").Value = "abc"
    SheetObj.Range("A4").Value = Now
        
    '閉じる
    BookObj.Close
    
    Set BookObj = Nothing
    Set RangeData = Nothing
    Set SheetObj = Nothing
End Sub

Excel(COM)

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;

namespace SampleCode; // C#10~

internal class SampleExcel
{
    static void Main(string[] args)
    {
        Excel.Application? application = null;
        Excel.Workbooks? workbooks = null;
        Excel.Workbook? workbook = null;
        Excel.Sheets? worksheets = null;
        Excel.Worksheet? worksheet = null;
        Excel.Range? cellData = null;

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");
            
            // Excelを開く
            application = new Excel.Application();
            application.Visible = true;

            // ブックを開く
            workbooks = application.Workbooks;
            workbook = workbooks.Open(filePath);

            // シートを取得
            worksheets = workbook.Sheets;
            worksheet = worksheets["Sheet1"];

            cellData = worksheet.Range["A1"];
            cellData.Value = 1;
            CleanUpComObject(ref cellData);

            cellData = worksheet.Range["A2"];
            cellData.Value = 1.1;
            CleanUpComObject(ref cellData);

            cellData = worksheet.Range["A3"];
            cellData.Value = "abc";
            CleanUpComObject(ref cellData);

            cellData = worksheet.Range["A4"];
            cellData.Value = DateTime.Now;
            CleanUpComObject(ref cellData);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            CleanUpComObject(ref cellData);
            CleanUpComObject(ref worksheet);
            CleanUpComObject(ref worksheets);
            CleanUpComObject(ref workbook, true, true);
            CleanUpComObject(ref workbooks);
            CleanUpComObject(ref application);
        }
    }

    static void CleanUpComObject<T>(ref T comObject, bool shouldClose = true, bool saveChanges = false)
    {
        // フラグによってWorkbookはClose / ApplicationはQuitする
        if (shouldClose && comObject != null)
        {
            // 型をチェックする
            if (comObject is Microsoft.Office.Interop.Excel.Workbook workbook)
            {
                // Workbookの場合
                workbook.Close(saveChanges);
            }
            else if (comObject is Microsoft.Office.Interop.Excel.Application application)
            {
                // Applicationの場合
                application.Quit();
            }
        }

        // Objectを解放
        if (comObject != null && Marshal.IsComObject(comObject))
        {
            Marshal.ReleaseComObject(comObject);
            comObject = default!;
        }
    }
}

補足:Microsoft.Office.Interop.Excel でオブジェクトの解放について

ClosedXML

using ClosedXML.Excel;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleClosedXML
{
    static void Main(string[] args)
    {
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");
            
            // ブックを開く、読み書きモード、共有なし(排他)
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            using (var workbook = new XLWorkbook(stream))
            {
                IXLWorksheet? worksheet = null;

                if(!workbook.TryGetWorksheet("Sheet1", out worksheet))
                {
                    throw new Exception("Sheet1シートがありませんでした");
                }

                worksheet.Cell("A1").Value = 1;
                worksheet.Cell("A2").Value = 1.1;
                worksheet.Cell("A3").Value = "abc";
                worksheet.Cell("A4").Value = DateTime.Now;

                workbook.Save();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

EPPlus

using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleEPPlus
{
    static void Main(string[] args)
    {
        // Ver8.0のソースです
        // 非商用個人利用の場合 名前を設定
        ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // メモリにすべて取り込む。これなら遅延でStreamにアクセスするような問題が発生しない
            byte[] fileBytes = File.ReadAllBytes(filePath);
            using (var readStream = new MemoryStream(fileBytes))
            using (var package = new ExcelPackage(readStream))
            {
                // シートを取得
                var worksheet = package.Workbook.Worksheets["Sheet1"];

                worksheet.Cells["A1"].Value = 1;
                worksheet.Cells["A2"].Value = 1.1;
                worksheet.Cells["A3"].Value = "abc";
                worksheet.Cells["A4"].Value = DateTime.Now.ToString("yyyy/MM/dd");

                // あらためて書き込み用としてStreamを開く
                using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // 書き込み
                    package.SaveAs(writeStream);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"エラー: {ex.Message}");
        }
    }
}

ExcelDataReader

読み取りのみのライブラリのためなし

NPOI

□xls

using NPOI.HSSF.UserModel;
using System;
using System.IO;
using System.Reflection;


namespace SampleCode; // C#10~

internal class SampleNPOI_xls
{
    static void Main(string[] args)
    {
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xls");

            // メモリにすべて取り込む。これなら遅延でStreamにアクセスするような問題が発生しない
            byte[] fileBytes = File.ReadAllBytes(filePath);
            using (var readStream = new MemoryStream(fileBytes))
            using (var workbook = new HSSFWorkbook(readStream))
            {
                // シートを取得
                var worksheet = workbook.GetSheet("Sheet1");

                // xls,xlsx共通で該当セルの情報がなければnullになるとのこと
                // 空=nullではないとのこと

                // A1セル
                var row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                var cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1);

                // A2セル
                row = worksheet.GetRow(1) ?? worksheet.CreateRow(1);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1.1);

                // A3セル
                row = worksheet.GetRow(2) ?? worksheet.CreateRow(2);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue("abc");

                // A4セル
                row = worksheet.GetRow(3) ?? worksheet.CreateRow(3);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(DateTime.Now);

                // あらためて書き込み用としてStreamを開く
                using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // 書き込み
                    workbook.Write(writeStream);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

□xlsx

using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleNPOI_xlsx
{
    static void Main(string[] args)
    {
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            // メモリにすべて取り込む。これなら遅延でStreamにアクセスするような問題が発生しない
            byte[] fileBytes = File.ReadAllBytes(filePath);
            using (var readStream = new MemoryStream(fileBytes))
            using (var workbook = new XSSFWorkbook(readStream))
            {
                // シートを取得
                var worksheet = workbook.GetSheet("Sheet1");

                // xls,xlsx共通で該当セルの情報がなければnullになるとのこと
                // 空=nullではないとのこと

                // A1セル
                var row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                var cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1);

                // A2セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1.1);

                // A3セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue("abc");

                // A4セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(DateTime.Now);

                // あらためて書き込み用としてStreamを開く
                using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // 書き込み
                    workbook.Write(writeStream);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

□xls/xlsx対応版

Program.cs

using System;
using System.IO;
using System.Reflection;

namespace SampleCode; // C#10~

internal class SampleNPOI
{
    static void Main(string[] args)
    {
        try
        {
            // 実行ファイルのあるフォルダパス取得
            var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            if (folderPath == null) { return; }

            // Excelファイルパスを作成
            var filePath = Path.Combine(folderPath, "sample.xlsx");

            var extension = Path.GetExtension(filePath);

            // メモリにすべて取り込む。これなら遅延でStreamにアクセスするような問題が発生しない
            byte[] fileBytes = File.ReadAllBytes(filePath);
            using (var readStream = new MemoryStream(fileBytes))
            using (var workbook = WorkbookFactory.Create(readStream, extension))
            {
                // シートを取得
                var worksheet = workbook.GetSheet("Sheet1");

                // xls,xlsx共通で該当セルの情報がなければnullになるとのこと
                // 空=nullではないとのこと

                // A1セル
                var row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                var cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1);

                // A2セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(1.1);

                // A3セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue("abc");

                // A4セル
                row = worksheet.GetRow(0) ?? worksheet.CreateRow(0);
                cell = row.GetCell(0) ?? row.CreateCell(0);
                cell.SetCellValue(DateTime.Now);

                // あらためて書き込み用としてStreamを開く
                using (var writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // 書き込み
                    workbook.Write(writeStream);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

WorkbookFactory.cs

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;

namespace SampleCode; // C#10

public class WorkbookFactory
{
    public static IWorkbook Create(Stream stream, string extension)
    {
        extension = extension.ToLower();

        return extension switch
        {
            ".xls" => new HSSFWorkbook(stream),
            ".xlsx" => new XSSFWorkbook(stream),
            _ => throw new NotSupportedException("対象外の拡張子です")
        };
    }

    public static IWorkbook Create(string extension)
    {
        extension = extension.ToLower();

        return extension switch
        {
            ".xls" => new HSSFWorkbook(),
            ".xlsx" => new XSSFWorkbook(),
            _ => throw new NotSupportedException("対象外の拡張子です")
        };
    }
}
投稿日時: 2025-05-23 23:56:23
更新日時: 2025-05-26 14:57:26

最近の投稿

最近のコメント

タグ

アーカイブ

その他