using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using ぬずぬずライブラリ.ExcelData;
namespace ぬずぬずライブラリ
{
///
/// Excelファイルの表を、リストオブジェクトで表した形で抽出します。
/// 使用する場合は参照設定にMicrosoft.VisualBasicライブラリを追加してください。
///
public static class ExcelReader
{
private static string[] alphabet =
{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
///
/// Excelファイルを読み込みます。
/// 遅延バインディングで読み込むためExcelのバージョンに関係なく使えます。
///
///読み込んだ結果
public static Context Read(string fileName)
{
object objApp_Late = null;
object objBook_Late = null;
object objBooks_Late = null;
object objSheets_Late = null;
object objSheet_Late = null;
object objRange_Late = null;
object[] args;
Context context = new Context();
try
{
// クラスの型及びExcelインスタンスを取得します。
Type objClassType;
objClassType = Type.GetTypeFromProgID("Excel.Application");
objApp_Late = Activator.CreateInstance(objClassType);
// WorkBooksコレクションを取得します。
objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, objApp_Late, null);
// WorkBookを開きます。
args = new Object[1];
args[0] = fileName;
objBook_Late = objBooks_Late.GetType().InvokeMember("Open",
BindingFlags.InvokeMethod, null, objBooks_Late, args);
// WorkSheetsコレクションを取得します。
objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, objBook_Late, null);
int sheets = int.Parse((objSheets_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objSheets_Late, null)).ToString());
// シート枚数分データテーブルを作成します。
// セルデータはデータテーブルにシートと同じように配置します。
for (int sheet = 1; sheet <= sheets; sheet++)
{
// WorkSheetを取得します。
args = new Object[1];
args[0] = sheet;
objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objSheets_Late, args);
objRange_Late = objSheet_Late.GetType().InvokeMember("UsedRange",
BindingFlags.GetProperty, null, objSheet_Late, null);
// セルデータを2次元配列にいっぺんに読み込みます。
Object[,] tmpTable;
tmpTable = (System.Object[,])(objRange_Late.GetType().InvokeMember("Value",
BindingFlags.GetProperty, null, objRange_Late, null));
Sheet table = new Sheet();
if (tmpTable == null) continue;
int rows = tmpTable.GetUpperBound(0);
int cols = tmpTable.GetUpperBound(1);
// Null文字を検出して最適有効範囲を求めます。
for (int row = rows; row > 0; row--)
{
for (int col = 1; col <= cols; col++)
{
if (tmpTable[row, col] == null)
{
continue;
}
if (tmpTable[row, col].ToString() != "")
{
rows = row;
goto LOOPEND1;
}
}
rows = row - 1;
}
LOOPEND1:
for (int col = cols; col > 0; col--)
{
for (int row = 1; row <= rows; row++)
{
if (tmpTable[row, col] == null)
{
continue;
}
else if (tmpTable[row, col].ToString() != "")
{
cols = col;
goto LOOPEND2;
}
}
cols = col - 1;
}
LOOPEND2:
// データテーブルにセルデータを代入します。
for (int row = 0; row < rows; row++)
{
Row newRow = new Row();
for (int col = 0; col < cols; col++)
{
string value = "";
if (tmpTable[row + 1, col + 1] != null)
{
value = tmpTable[row + 1, col + 1].ToString();
}
newRow.Add(value);
}
table.Add(newRow);
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
context.Add(table);
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
args = new Object[1];
args[0] = false;
// 変更を保存しますがダイアログを出さないようにします。
objApp_Late.GetType().InvokeMember("DisplayAlerts",
BindingFlags.SetProperty, null, objApp_Late, args);
// アプリケーションを終了します。
objApp_Late.GetType().InvokeMember("Quit",
BindingFlags.InvokeMethod, null, objApp_Late, null);
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
if (objBooks_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBooks_Late);
objBooks_Late = null;
}
if (objBook_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
if (objSheets_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheets_Late);
objSheets_Late = null;
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objApp_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp_Late);
objApp_Late = null;
}
}
return context;
}
///
/// ファイル名を指定してExcelファイルを開き、指定されたセルを選択します。
///
/// 行番号
/// 列番号
/// シート番号
/// ファイル名
public static void Open(int rowNumber, int colNumber, int sheetNumber, string fileName)
{
Open(rowNumber, ColumnNumberToAlphabet(colNumber), sheetNumber, fileName);
}
///
/// ファイル名を指定してExcelファイルを開き、指定されたセルを選択します。
///
/// 行番号
/// 列名(アルファベット)
/// シート番号
/// ファイル名
public static void Open(int rowNumber, string colAlphabet, int sheetNumber, string fileName)
{
object objApp_Late = null;
object objBook_Late = null;
object objBooks_Late = null;
object objSheets_Late = null;
object objSheet_Late = null;
object objRange_Late = null;
object[] args;
try
{
// クラスの型及びExcelインスタンスを取得します。
string pID = "Excel.Application";
try
{
objApp_Late = Marshal.GetActiveObject(pID);
}
catch
{
Type objClassType;
objClassType = Type.GetTypeFromProgID(pID);
objApp_Late = Activator.CreateInstance(objClassType);
}
// 見えるようにします。
args = new Object[1];
args[0] = true;
objApp_Late.GetType().InvokeMember("Visible",
BindingFlags.SetProperty, null, objApp_Late, args);
Microsoft.VisualBasic.Interaction.AppActivate("Microsoft Excel");
// WorkBooksコレクションを取得します。
objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, objApp_Late, null);
int count = int.Parse(objBooks_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objBooks_Late, null).ToString());
for (int k = 1; k <= count; k++)
{
args = new Object[1];
args[0] = k;
// WorkBookを取得します。
objBook_Late = objBooks_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objBooks_Late, args);
string fullName = (objBook_Late.GetType().InvokeMember("FullName",
BindingFlags.GetProperty, null, objBook_Late, null)).ToString();
// 目的のファイルじゃない場合は解放して次を調べます。
if (fullName != fileName)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
}
// WorkBookが開かれていない場合はここで開きます。
if (objBook_Late == null)
{
args = new Object[1];
args[0] = fileName;
objBook_Late = objBooks_Late.GetType().InvokeMember("Open",
BindingFlags.InvokeMethod, null, objBooks_Late, args);
}
// WorkSheetsコレクションを取得します。
objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, objBook_Late, null);
count = int.Parse(objSheets_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objSheets_Late, null).ToString());
if (count < sheetNumber)
{
throw (new Exception("指定されたシートが存在しません。"));
}
// WorkSheetを取得します。
args = new Object[1];
args[0] = sheetNumber;
objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objSheets_Late, args);
// WorkSheetをアクティブにします(こうしないとセルが選択できなかった)。
objSheet_Late.GetType().InvokeMember("Activate",
BindingFlags.GetProperty, null, objSheet_Late, null);
// セルを取得します。
args = new Object[1];
args[0] = colAlphabet + rowNumber.ToString();
objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
BindingFlags.GetProperty, null, objSheet_Late, args);
// セルを選択します。
objRange_Late.GetType().InvokeMember("Select",
BindingFlags.InvokeMethod, null, objRange_Late, null);
}
catch
{
throw (new Exception("指定されたExcelを開けませんでした。"));
}
finally
{
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
if (objBooks_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBooks_Late);
objBooks_Late = null;
}
if (objBook_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
if (objSheets_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheets_Late);
objSheets_Late = null;
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objApp_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp_Late);
objApp_Late = null;
}
}
}
private static string ColumnNumberToAlphabet(int colNumber)
{
string c1 = alphabet[colNumber % 26];
string c2 = 26 < colNumber ? alphabet[colNumber / 26 - 1] : "";
return c2 + c1;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using ぬずぬずライブラリ.ExcelData;
namespace ぬずぬずライブラリ
{
///
/// Excelファイルの表を、リストオブジェクトで表した形で抽出します。
/// 使用する場合は参照設定にMicrosoft.VisualBasicライブラリを追加してください。
///
public static class ExcelReader
{
private static string[] alphabet =
{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
///
/// Excelファイルを読み込みます。
/// 遅延バインディングで読み込むためExcelのバージョンに関係なく使えます。
///
///
public static Context Read(string fileName)
{
object objApp_Late = null;
object objBook_Late = null;
object objBooks_Late = null;
object objSheets_Late = null;
object objSheet_Late = null;
object objRange_Late = null;
object[] args;
Context context = new Context();
try
{
// クラスの型及びExcelインスタンスを取得します。
Type objClassType;
objClassType = Type.GetTypeFromProgID("Excel.Application");
objApp_Late = Activator.CreateInstance(objClassType);
// WorkBooksコレクションを取得します。
objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, objApp_Late, null);
// WorkBookを開きます。
args = new Object[1];
args[0] = fileName;
objBook_Late = objBooks_Late.GetType().InvokeMember("Open",
BindingFlags.InvokeMethod, null, objBooks_Late, args);
// WorkSheetsコレクションを取得します。
objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, objBook_Late, null);
int sheets = int.Parse((objSheets_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objSheets_Late, null)).ToString());
// シート枚数分データテーブルを作成します。
// セルデータはデータテーブルにシートと同じように配置します。
for (int sheet = 1; sheet <= sheets; sheet++)
{
// WorkSheetを取得します。
args = new Object[1];
args[0] = sheet;
objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objSheets_Late, args);
objRange_Late = objSheet_Late.GetType().InvokeMember("UsedRange",
BindingFlags.GetProperty, null, objSheet_Late, null);
// セルデータを2次元配列にいっぺんに読み込みます。
Object[,] tmpTable;
tmpTable = (System.Object[,])(objRange_Late.GetType().InvokeMember("Value",
BindingFlags.GetProperty, null, objRange_Late, null));
Sheet table = new Sheet();
if (tmpTable == null) continue;
int rows = tmpTable.GetUpperBound(0);
int cols = tmpTable.GetUpperBound(1);
// Null文字を検出して最適有効範囲を求めます。
for (int row = rows; row > 0; row--)
{
for (int col = 1; col <= cols; col++)
{
if (tmpTable[row, col] == null)
{
continue;
}
if (tmpTable[row, col].ToString() != "")
{
rows = row;
goto LOOPEND1;
}
}
rows = row - 1;
}
LOOPEND1:
for (int col = cols; col > 0; col--)
{
for (int row = 1; row <= rows; row++)
{
if (tmpTable[row, col] == null)
{
continue;
}
else if (tmpTable[row, col].ToString() != "")
{
cols = col;
goto LOOPEND2;
}
}
cols = col - 1;
}
LOOPEND2:
// データテーブルにセルデータを代入します。
for (int row = 0; row < rows; row++)
{
Row newRow = new Row();
for (int col = 0; col < cols; col++)
{
string value = "";
if (tmpTable[row + 1, col + 1] != null)
{
value = tmpTable[row + 1, col + 1].ToString();
}
newRow.Add(value);
}
table.Add(newRow);
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
context.Add(table);
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
args = new Object[1];
args[0] = false;
// 変更を保存しますがダイアログを出さないようにします。
objApp_Late.GetType().InvokeMember("DisplayAlerts",
BindingFlags.SetProperty, null, objApp_Late, args);
// アプリケーションを終了します。
objApp_Late.GetType().InvokeMember("Quit",
BindingFlags.InvokeMethod, null, objApp_Late, null);
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
if (objBooks_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBooks_Late);
objBooks_Late = null;
}
if (objBook_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
if (objSheets_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheets_Late);
objSheets_Late = null;
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objApp_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp_Late);
objApp_Late = null;
}
}
return context;
}
///
/// ファイル名を指定してExcelファイルを開き、指定されたセルを選択します。
///
/// 行番号
/// 列番号
/// シート番号
/// ファイル名
public static void Open(int rowNumber, int colNumber, int sheetNumber, string fileName)
{
Open(rowNumber, ColumnNumberToAlphabet(colNumber), sheetNumber, fileName);
}
///
/// ファイル名を指定してExcelファイルを開き、指定されたセルを選択します。
///
/// 行番号
/// 列名(アルファベット)
/// シート番号
/// ファイル名
public static void Open(int rowNumber, string colAlphabet, int sheetNumber, string fileName)
{
object objApp_Late = null;
object objBook_Late = null;
object objBooks_Late = null;
object objSheets_Late = null;
object objSheet_Late = null;
object objRange_Late = null;
object[] args;
try
{
// クラスの型及びExcelインスタンスを取得します。
string pID = "Excel.Application";
try
{
objApp_Late = Marshal.GetActiveObject(pID);
}
catch
{
Type objClassType;
objClassType = Type.GetTypeFromProgID(pID);
objApp_Late = Activator.CreateInstance(objClassType);
}
// 見えるようにします。
args = new Object[1];
args[0] = true;
objApp_Late.GetType().InvokeMember("Visible",
BindingFlags.SetProperty, null, objApp_Late, args);
Microsoft.VisualBasic.Interaction.AppActivate("Microsoft Excel");
// WorkBooksコレクションを取得します。
objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, objApp_Late, null);
int count = int.Parse(objBooks_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objBooks_Late, null).ToString());
for (int k = 1; k <= count; k++)
{
args = new Object[1];
args[0] = k;
// WorkBookを取得します。
objBook_Late = objBooks_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objBooks_Late, args);
string fullName = (objBook_Late.GetType().InvokeMember("FullName",
BindingFlags.GetProperty, null, objBook_Late, null)).ToString();
// 目的のファイルじゃない場合は解放して次を調べます。
if (fullName != fileName)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
}
// WorkBookが開かれていない場合はここで開きます。
if (objBook_Late == null)
{
args = new Object[1];
args[0] = fileName;
objBook_Late = objBooks_Late.GetType().InvokeMember("Open",
BindingFlags.InvokeMethod, null, objBooks_Late, args);
}
// WorkSheetsコレクションを取得します。
objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, objBook_Late, null);
count = int.Parse(objSheets_Late.GetType().InvokeMember("Count",
BindingFlags.GetProperty, null, objSheets_Late, null).ToString());
if (count < sheetNumber)
{
throw (new Exception("指定されたシートが存在しません。"));
}
// WorkSheetを取得します。
args = new Object[1];
args[0] = sheetNumber;
objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, objSheets_Late, args);
// WorkSheetをアクティブにします(こうしないとセルが選択できなかった)。
objSheet_Late.GetType().InvokeMember("Activate",
BindingFlags.GetProperty, null, objSheet_Late, null);
// セルを取得します。
args = new Object[1];
args[0] = colAlphabet + rowNumber.ToString();
objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
BindingFlags.GetProperty, null, objSheet_Late, args);
// セルを選択します。
objRange_Late.GetType().InvokeMember("Select",
BindingFlags.InvokeMethod, null, objRange_Late, null);
}
catch
{
throw (new Exception("指定されたExcelを開けませんでした。"));
}
finally
{
if (objRange_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRange_Late);
objRange_Late = null;
}
if (objBooks_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBooks_Late);
objBooks_Late = null;
}
if (objBook_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objBook_Late);
objBook_Late = null;
}
if (objSheets_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheets_Late);
objSheets_Late = null;
}
if (objSheet_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet_Late);
objSheet_Late = null;
}
if (objApp_Late != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp_Late);
objApp_Late = null;
}
}
}
private static string ColumnNumberToAlphabet(int colNumber)
{
string c1 = alphabet[colNumber % 26];
string c2 = 26 < colNumber ? alphabet[colNumber / 26 - 1] : "";
return c2 + c1;
}
}
}