ASP.NETでエクセル操作 その2
これから実装方法について説明します。エクセルを扱うクラスに必要なオブジェクトのメンバ変数を設定します。デストラクタ、または解放用のメソッドでエクセルの参照を解放します。下記のSampleClassは、エクセルを扱う上でのひな形です。必要に応じてメソッドを生成していくことになります。
using System;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
namespace studio_onestep
{
public sealed class SampleClass
{
#region Excel関連の変数
private Excel.Application _excel = null;
private Excel.Workbooks _books = null;
private Excel.Workbook _book = null;
private Excel.Sheets _sheets = null;
private Excel.Worksheet _sheet = null;
private Excel.Range _cells = null;
#endregion
//エクセルを生成する
public SampleClass()
{
this._excel = new Excel.Application();
this._excel.Visible = false;
this._excel.DisplayAlerts = false;
this._excel.ScreenUpdating = false;
this._books = this._excel.Workbooks;
this._book = this._books.Add(Missing.Value);
this._sheets = this._book.Worksheets;
this._sheet = (Excel.Worksheet)this._sheets[1];
this._cells = this._sheet.Cells;
}
/// <summary>
/// セルに値を設定します
/// </summary>
/// <param name="rowNum">行番号</param>
/// <param name="colStartNum">列の開始番号</param>
/// <param name="values">値の配列</param>
private void _setCellValues(int rowNum, int colStartNum,
string[] values)
{
for(int c = 0; c < values.Length; c++)
{
if(!string.IsNullOrEmpty(values[c]))
{
Excel.Range cell = (Excel.Range)this._cells.get_Item(rowNum, (colStartNum + c));
cell.Value = values[c];
Marshal.FinalReleaseComObject(cell);
}
}
}
//エクセルを解放する
~SampleClass()
{
if(this._cells != null)
{
Marshal.FinalReleaseComObject(this._cells);
this._cells = null;
}
if(this._sheet != null)
{
Marshal.FinalReleaseComObject(this._sheet);
this._sheet = null;
}
if(this._sheets != null)
{
Marshal.FinalReleaseComObject(this._sheets);
this._sheets = null;
}
if(this._book != null)
{
Marshal.FinalReleaseComObject(this._book);
this._book = null;
}
if(this._books != null)
{
Marshal.FinalReleaseComObject(this._books);
this._books = null;
}
if(this._excel != null)
{
Marshal.FinalReleaseComObject(this._excel);
this._excel = null;
}
}
/// <summary>
/// ワークブックを保存して、閉じます。
/// </summary>
/// <param name="filename"></param>
public void SaveBook(string filename)
{
this._book.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
this._book.Close(false, Type.Missing, Type.Missing);
}
}
}
« ASP.NETでエクセル操作 その1 | トップページ | ASP.NETでエクセル操作 その3 »
「03 web」カテゴリの記事
- ASP.NETでエクセル操作 その4(2008.08.18)
- ASP.NETでエクセル操作 その3(2008.08.15)
- ASP.NETでエクセル操作 その2(2008.08.14)
- ASP.NETでエクセル操作 その1(2008.08.13)
- ASP.NET AJAX AutoCompleteコントロール(2008.05.01)
コメント