ExcelVBA
SaveAsでファイルパスを指定する
Sub Sample()
Dim BookObj As Workbook
Dim FilePath As String
'新規ブック作成
Set BookObj = Workbooks.Add
'保存するファイルパス
FilePath = ThisWorkbook.Path & "\sample.xlsx"
'名前つけて保存
BookObj.SaveAs Filename:=FilePath
Set BookObj = Nothing
End Sub
ただし、ファイルが既にある場合は「この場所に 'XXXX'という名前のファイルが既にあります。置き換えますか?」
と表示されるため、ファイルがある場合も上書きするのであれば、以下のようにします
Sub Sample()
Dim BookObj As Workbook
Dim FilePath As String
'新規ブック作成
Set BookObj = Workbooks.Add
'保存するファイルパス
'ファイルパス作成
FilePath = ThisWorkbook.Path & "\sample.xls"
'同一ファイルがあった場合の警告表示を無効とする
Application.DisplayAlerts = False
'名前つけて保存
BookObj.SaveAs Filename:=FilePath
'警告表示を有効に戻す
Application.DisplayAlerts = True
Set BookObj = Nothing
End Sub
もし、ファイルが既にある場合に上書きしたくない場合は事前にファイル存在チェックをして処理を止めればよいでしょう
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;
workbook = workbooks.Add();
// 警告表示を無効にする
application.DisplayAlerts = false;
// 名前つけて保存
workbook.SaveAs2(filePath);
// 警告表示を有効に戻す
application.DisplayAlerts = false;
}
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
ファイルパスと、Streamを使った方法
□ファイルパスで名前を付けて保存
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 workbook = new XLWorkbook())
{
// シートが一つもないブックは保存でエラーになるので追加
var sheet = workbook.AddWorksheet("Sheet1");
// 名前をつけて保存
workbook.SaveAs(filePath);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
□FileStreamで名前を付けて保存
using ClosedXML.Excel;
using System;
using System.IO;
using System.Reflection;
namespace SampleCode; // C#10~
internal class SampleClosedXML
{
static void Main(string[] args)
{
var filePath = string.Empty;
try
{
// 実行ファイルのあるフォルダパス取得
var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
if (folderPath == null) { return; }
// Excelファイルパスを作成
filePath = Path.Combine(folderPath, "sample.xlsx");
// ファイル出力用のストリームを作成(まだ中身は空のものが作られる)
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
// メモリ上にワークブックを作成(この時点ではストリームとは未接続)
using (var workbook = new XLWorkbook())
{
// シートが一つもないブックは保存でエラーになるので追加
var sheet = workbook.AddWorksheet("Sheet1");
// 作成したワークブックをストリームに保存(初めてファイルと紐づく)
workbook.SaveAs(stream);
}
}
catch (Exception ex)
{
// エラーが発生し、保存ができていなければ、空ファイルを作っただけなので、紛らわしいので消しておく
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
File.Delete(filePath);
}
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 package = new ExcelPackage())
{
// シートが一つもないブックは保存でエラーになるので追加
var worksheet = package.Workbook.Worksheets.Add("sample");
// 保存
package.SaveAs(filePath);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
FileStreamを使った場合は、ClosedXMLと同じなのでそちらを参照
ExcelDataReader
読み取りのみのライブラリのため保存はありません
NPOI
NPOIは、ファイルパスをうけとれないので、FileStreamで処理する
□xls
using NPOI.HSSF.UserModel;
using System.Reflection;
var filePath = "";
try
{
// 実行ファイルのあるフォルダパス取得
var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
if (folderPath == null) { return; }
// Excelファイルパスを作成
filePath = Path.Combine(folderPath, "sample.xls");
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (var workbook = new HSSFWorkbook())
{
// シートが一つもないブックは保存でエラーになるので追加
workbook.CreateSheet("Sheet1");
// 作成したワークブックをストリームに保存
workbook.Write(stream);
}
}
catch (Exception ex)
{
// エラーが発生し、保存ができていなければ、空ファイルを作っただけなので、紛らわしいので消しておく
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
File.Delete(filePath);
}
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 stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (var workbook = new XSSFWorkbook())
{
// シートなしでも保存はできてしまう
// sample.xlsxの一部の内容に問題が見つかりました。と出るのでシートは追加すること
workbook.CreateSheet("Sheet1");
// 作成したワークブックをストリームに保存
workbook.Write(stream);
}
}
catch (Exception ex)
{
// エラーが発生し、保存ができていなければ、空ファイルを作っただけなので、紛らわしいので消しておく
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
File.Delete(filePath);
}
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);
// ブックを開く、読み取りモード、共有は読み取りのみOK
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (var workbook = WorkbookFactory.Create(fileStream, extension))
{
// シートなしでも保存はできてしまう
// sample.xlsxの一部の内容に問題が見つかりました。と出るのでシートは追加すること
workbook.CreateSheet("Sheet1");
// 作成したワークブックをストリームに保存
workbook.Write(fileStream);
}
}
catch (Exception ex)
{
// エラーが発生し、保存ができていなければ、空ファイルを作っただけなので、紛らわしいので消しておく
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
File.Delete(filePath);
}
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("対象外の拡張子です")
};
}
}