August 11, 2009

Excel C# Helper

Ever need to work with Excel in C#? It is not fun at all. Here is a helper class for you:
using System;
using System.Collections.Generic;
using System.Text;

namespace JLFramework
{
class ExcelAgent
{
Excel._Worksheet _sheet;

int _row;
int _col;

int _defaultInteriorColorIndex;

public ExcelAgent(Excel._Worksheet sheet)
{
_sheet = sheet;
}

public void SetDefaultInteriorColorIndex(int colorIndex)
{
_defaultInteriorColorIndex = colorIndex;
}

public void Goto(int row, int col)
{
_row = row;
_col = col;
}

public void DrawEdge(Excel.XlBordersIndex side, Excel.XlLineStyle lineStyle, Excel.XlBorderWeight weight)
{
Excel.Range range = CurrentRange;
range.Borders[side].LineStyle = lineStyle;
range.Borders[side].Weight = weight;
}

public void WriteLine(string text)
{
_sheet.Cells[_row++, _col] = text;

if (GetInteriorColorIndex() == (int)Excel.Constants.xlNone)
SetInteriorColorIndex(_defaultInteriorColorIndex);
}

public void SetInteriorColorIndex(int colorIndex)
{
CurrentRange.Interior.ColorIndex = colorIndex;
}

public void SetFontColorIndex(int colorIndex)
{
CurrentRange.Font.ColorIndex = colorIndex;
}

public int CurrentRowIndex
{
get { return _row; }
}

public int CurrentColIndex
{
get { return _col; }
}

#region Private methods

private int GetInteriorColorIndex()
{
return (int) CurrentRange.Interior.ColorIndex;
}

private Excel.Range CurrentRange
{
get
{
return (Excel.Range)_sheet.Cells[_row, _col];
}
}

#endregion
}
}

No comments:

Post a Comment