2次元配列でごそっととってそれぞれをアクセスするほうが圧倒的に効率的です。
では、サンプルを書いておきます。

今回は、行列の数がわかっている設定としておきます。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelTest
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApplication = null;
Excel.Workbooks xlWorkbooks = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlWorksheet = null;
try
{
string filePath = Application.StartupPath + @"\Data.xlsx";
xlApplication = new Excel.Application();
xlApplication.Visible = true;
xlWorkbooks = xlApplication.Workbooks;
xlWorkbook = xlWorkbooks.Open(filePath);
xlSheets = xlWorkbook.Sheets;
xlWorksheet = xlSheets[1];
object[,] cellData = new object[10, 5]; //受け取るデータの個数分(行、列セル数を指定)
cellData = xlWorksheet.get_Range("A1", "E10").Value; //Cellsは激遅なのでRangeを利用します。
xlWorkbooks.Close();
xlApplication.Quit();
//データを出力 要素数は1から格納されています
for (int r = 1; r <= cellData.GetLength(0); r++)
{
for (int c = 1; c <= cellData.GetLength(1); c++)
{
Console.Write(string.Format(" {0} ", cellData[r, c]));
}
Console.WriteLine(string.Empty);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (xlSheets != null)
{
Marshal.FinalReleaseComObject(xlSheets);
}
if (xlWorkbook != null)
{
Marshal.FinalReleaseComObject(xlWorkbook);
}
if (xlWorkbooks != null)
{
Marshal.FinalReleaseComObject(xlWorkbooks);
}
if (xlApplication != null)
{
Marshal.FinalReleaseComObject(xlApplication);
}
}
}
}
}
0 件のコメント:
コメントを投稿