A1:A10の範囲を1000回取得する。現実的にある数値にしてみた。
Case1:get_Range
Case2:Cells 一度Rangeに置き換えてからCells
Case3:Cells 型変換して直接Cellsへ
using System;
using System.Diagnostics;
using System.Reflection;
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
{
xlApplication = new Excel.Application();
xlApplication.Visible = true;
xlWorkbooks = xlApplication.Workbooks;
xlWorkbook = xlWorkbooks.Add();
xlSheets = xlWorkbook.Sheets;
xlWorksheet = xlSheets[1];
Case1(xlWorksheet);
Case2(xlWorksheet);
Case3(xlWorksheet);
xlWorkbooks.Close();
xlApplication.Quit();
}
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);
}
}
}
static void Case1(Excel.Worksheet xlWorksheet)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Excel.Range xlRange = null;
for (int i = 0; i < 1000; i++)
{
xlRange = xlWorksheet.get_Range("A1", "A10");
Marshal.FinalReleaseComObject(xlRange);
}
sw.Stop();
Console.WriteLine("[{0}]{1}", MethodBase.GetCurrentMethod().Name, sw.Elapsed);
}
static void Case2(Excel.Worksheet xlWorksheet)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Excel.Range stRange = null;
Excel.Range edRange = null;
Excel.Range xlRange = null;
for (int i = 0; i < 1000; i++)
{
stRange = xlWorksheet.Cells[1, 1];
edRange = xlWorksheet.Cells[1, 10];
xlRange = xlWorksheet.get_Range(stRange, edRange);
Marshal.FinalReleaseComObject(stRange);
Marshal.FinalReleaseComObject(edRange);
Marshal.FinalReleaseComObject(xlRange);
}
sw.Stop();
Console.WriteLine("[{0}]{1}", MethodBase.GetCurrentMethod().Name, sw.Elapsed);
}
static void Case3(Excel.Worksheet xlWorksheet)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Excel.Range xlRange = null;
for (int i = 0; i < 1000; i++)
{
xlRange = xlWorksheet.get_Range((Excel.Range)xlWorksheet.Cells[1, 1], (Excel.Range)xlWorksheet.Cells[1, 10]);
Marshal.FinalReleaseComObject(xlRange);
}
sw.Stop();
Console.WriteLine("[{0}]{1}", MethodBase.GetCurrentMethod().Name, sw.Elapsed);
}
}
}
[Case1]00:00:04.4432538 [Case2]00:00:19.4220595 [Case3]00:00:18.9210169
get_Rangeが速い模様。
0 件のコメント:
コメントを投稿