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
未対応