ExcelVBA

VBAだとWritePasswordにパスを設定しておけば、開いた際にパスを求められるようになります

Sub Sample()
    Dim BookObj     As Workbook
    Dim FilePath    As String
    Dim WritePass   As String: Pass = "test"
    
    'ファイルパス作成
    FilePath = ThisWorkbook.Path & "\sample.xlsx"
    
    '書き込みパスワード付きExcelを開く
    Set BookObj = Workbooks.Open(FilePath, WriteResPassword:=WritePass)
    
    Set BookObj = Nothing
End Sub

Excel(COM)

Excel(COM)も同様です。

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

namespace SampleCode; // C#10~

internal class SampleExcel
{
    static void Main(string[] args)
    {
        Excel.Application? application = null;
        Excel.Workbooks? workbooks = null;
        Excel.Workbook? workbook = 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;

            // 書き込みパスワード
            var writePass = "test";

            // 書き込みパスワードでブックを開く
            workbook = workbooks.Open(Filename: filePath, WriteResPassword: writePass);  // 名前付き引数がおすすめ
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            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!;
        }
    }
}

ClosedXML

未対応

EPPlus

未対応

ExcelDataReader

未対応

NPOI

未対応

参考:
ClosedXML, ExcelDataReader, EPPlus, NPOIがパスワード解除について

投稿日時: 2025-05-10 18:18:10
更新日時: 2025-05-24 09:25:24

通常のxlsxのファイルは拡張子をzipにし、展開するとファイルの中身が確認できます

それに対し、読み取りパスワードを設定すると、ファイル全体が暗号化されるため、同様のことはできません。

暗号化されているためzip構造になっていないということですね。

GPTの予想では、ファイル全体の暗号化/複合化の対応まで対処するのが大変なので、これらのライブラリでは読み取りパスワードの解除機能はないのではないかとのこと。

書き込みパスワードの場合はどうかというと、書き込みパスワードであれば閲覧できないわけではないので、
zip化して開いて中身をみることができます

xl/workbook.xml を開くと以下のように埋め込まれていて

<fileSharing userName="ユーザー名" algorithmName="SHA-512" hashValue="/Sjoy10H3uY10Lh1Ew7UkIlk8b6ZAVNvvpd6LUsgoFJFYrkn7QJ2e2nAgguO1gdRRWwK9NrGpaduJG5y6nZsLA==" saltValue="3GWq9TRXLA7h35x78qzkHQ==" spinCount="100000"/>

ざっくりとした解釈では、入力された書き込みパスワードにsaltをつけてハッシュ化し、
もとまった値に対してもsaltをつけてハッシュ化することを100000をくりかえした結果をhasValueに設定している

詳細の仕様については、 以下に仕様ありとのこと
MS-OFFCRYPTO
https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/3c34d72a-1a61-4b52-a893-196f9157f083

生成AIにいろいろ確認した内容のまとめ

ライブラリ 読み取りパスワード解除 書き込みパスワード解除 書き込みパスワード設定 シートの保護設定 シート保護解除して書き込み
ClosedXML ×非対応 ×非対応 ×非対応 〇対応 〇対応
EPPlus ×非対応 ×非対応 〇対応 〇対応 〇対応
ExcelDataReader ×非対応 ×非対応 ×非対応 ×非対応 ×非対応
NPOI ×非対応 ×非対応 ×非対応 〇対応 〇対応

EPPlusにおいては、書き込みパスワードの設定が可能であり、
シートの保護関係については、ExcelDataReader以外は対応している様子です

極論をいえば、XMLファイルを操作するだけなので、ファイル全体が暗号化されていなければ、ただの文字列が書き込まれているだけなので
ライブラリ側で無視してしまえば、書き込みパスワードもシートの保護もなかったことになってしまうという話ですが・・・

実際は、シートの保護は対応しても、書き込みパスワードについては対応していないのが現状のようです。。

生成AIの予想では倫理的なものではという話ですが、ちょっと謎です

投稿日時: 2025-05-10 18:17:10
更新日時: 2025-05-11 05:53:11

ExcelVBA

Open時、ReadOnlyをTrueにすることで読み取り専用で開く

Sub Sample()
    Dim BookObj As Workbook
    Dim FilePath    As String
    
    'ファイルパス作成
    FilePath = ThisWorkbook.Path & "\sample.xlsx"
    
    'ブックを開く
    Set BookObj = Workbooks.Open(FilePath, ReadOnly:=True)
    
    Set BookObj = Nothing
End Sub

Excel(COM)

VBA同様 ReadOnlyにTrueを指定して、読み取り専用で開く

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

namespace SampleCode; // C#10~

internal class SampleExcel
{
    static void Main(string[] args)
    {
        Excel.Application? application = null;
        Excel.Workbooks? workbooks = null;
        Excel.Workbook? workbook = 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;
            // ブックを開く(ReadOnlyの項目をtrue)
            workbook = workbooks.Open(Filename: filePath, ReadOnly: true); // 名前付き引数がおすすめ
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            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!;
        }
    }
}

ClosedXML

FileStreamで読み取り専用で開く

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.Read, FileShare.Read))
            using (var workbook = new XLWorkbook(stream))
            {
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

EPPlus

FileStreamで読み取り専用で開く

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");

            // ブックを開く、読み取りモード、共有は読み取りのみOK
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (var package = new ExcelPackage(stream))
            {
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

ExcelDataReader

FileAccessがReadであろうがなかろうが、読み取りのみのライブラリのため書き込む機能なし

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");

            // ブックを開く、読み取りモード、共有は読み取りのみOK
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (var reader = ExcelReaderFactory.CreateReader(fileStream))
            {
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

NPOI

FileStreamで読み取り専用で開く
□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");

            // ブックを開く、読み取りモード、共有は読み取りのみOK
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var workbook = new HSSFWorkbook(fileStream);
            }
        }
        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");

            // ブックを開く、読み取りモード、共有は読み取りのみOK
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var workbook = new XSSFWorkbook(fileStream);
            }
        }
        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);

            // ブックを開く、読み取りモード、共有は読み取りのみOK
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (var workbook = WorkbookFactory.Create(fileStream, extension))
            { 
            }
        }
        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-10 16:10:10
更新日時: 2025-05-24 09:06:24

最近の投稿

最近のコメント

タグ

アーカイブ

その他