ExcelVBA
Sub Sample()
Dim BookObj As Workbook
Dim CellData As Range
Dim FilePath As String
Dim RangeData As Range
Dim SheetObj As Worksheet
'ファイルパス作成
FilePath = ThisWorkbook.Path & "\sample.xlsx"
'ブックを開く
Set BookObj = Workbooks.Open(FilePath)
'シート取得
Set SheetObj = BookObj.Sheets("Sheet1")
'A1形式
Debug.Print SheetObj.Range("A1").Value
'R1C1形式
Debug.Print SheetObj.Cells(1, 1).Value
'閉じる
BookObj.Close
Set BookObj = Nothing
Set CellData = 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? cellData1 = null;
Excel.Range? cellData2 = 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"];
// A1形式
cellData1 = worksheet.Range["A1"];
Console.WriteLine(cellData1.Value);
// R1C1形式
cellData2 = worksheet.Cells[1, 1];
Console.WriteLine(cellData2.Value);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
CleanUpComObject(ref cellData1);
CleanUpComObject(ref cellData2);
CleanUpComObject(ref worksheet);
CleanUpComObject(ref worksheets);
CleanUpComObject(ref workbook);
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シートがありませんでした");
}
// A1形式
Console.WriteLine(worksheet.Cell("A1").Value);
// R1C1形式
Console.WriteLine(worksheet.Cell(1, 1).Value);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
EPPlus
using OfficeOpenXml;
using System;
using System.IO;
using System.IO.Pipes;
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))
{
// シートを取得
var worksheet = package.Workbook.Worksheets["Sheet1"];
// A1形式
Console.WriteLine(worksheet.Cells["A1"].Value);
// R1C1形式
Console.WriteLine(worksheet.Cells[1, 1].Value); // 行, 列
}
}
catch (Exception ex)
{
Console.WriteLine($"エラー: {ex.Message}");
}
}
}
ExcelDataReader
using ExcelDataReader;
using System;
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();
// シート取得
var worksheet = result.Tables["Sheet1"];
// A1形式は存在しない
// R1C1形式(0から始まる)
Console.WriteLine(worksheet.Rows[0][0]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 列を表す数値から列を表す文字列に変換する
static string ConvertColumnNumToStr(int colNum)
{
var colStr = string.Empty;
while (colNum > 0)
{
int modulo = (colNum - 1) % 26;
colStr = Convert.ToChar('A' + modulo) + colStr;
colNum = (colNum - modulo) / 26;
}
return colStr;
}
}
NPOI
xls
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
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");
// ブックを開く、読み取りモード、共有なし(排他)
using (var stRead = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
using (var workbook = new HSSFWorkbook(stRead))
{
// シートを取得
var worksheet = workbook.GetSheet("Sheet1");
// A1形式は存在しない
// R1C1形式(0から始まる)
Console.WriteLine(worksheet.GetRow(0).GetCell(0).StringCellValue);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
xlsx
using NPOI.SS.Util;
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");
// ブックを開く、読み取りモード、共有なし(排他)
using (var stRead = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
using (var workbook = new XSSFWorkbook(stRead))
{
// シートを取得
var worksheet = workbook.GetSheet("Sheet1");
// A1形式は存在しない
// R1C1形式(0から始まる)
Console.WriteLine(worksheet.GetRow(0).GetCell(0).StringCellValue);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
xlsもxlsxも扱う場合
Program.cs
using NPOI.SS.Util;
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);
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
using (var workbook = WorkbookFactory.Create(fileStream, extension))
{
// シートを取得
var worksheet = workbook.GetSheet("Sheet1");
// A1形式は存在しない
// R1C1形式(0から始まる)
Console.WriteLine(worksheet.GetRow(0).GetCell(0).StringCellValue);
}
}
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("対象外の拡張子です")
};
}
}