总是感觉对于C#中读取Excel文件是非常麻烦,还是决定自己来封装一个基于COM接口的类解决这个问题。
整体设计以及实现如下(首先请加入对于Microsoft.CSharp以及Office Object Library、Excel Object Library 譬如12.0版本的引用):
public sealed class ExcelFileReader
{
private string m_strFileName = null;
private Application m_application = null;
private Workbook m_workBook = null;
private int m_totalSheets = 0;
private int m_activeSheet = 0;
private int m_sheetColumns = 0;
private int m_sheetRows = 0;
public ExcelFileReader(string fileName)
{
m_strFileName = fileName;
}
public string FileName
{
get { return this.m_strFileName; }
set { this.m_strFileName = value; }
}
public int TotalSheets
{
get { return this.m_totalSheets; }
}
public int ActiveSheetIndex
{
get { return this.m_activeSheet; }
}
public int SheetColumns
{
get { return this.m_sheetColumns; }
}
public int SheetRows
{
get { return this.m_sheetRows; }
}
public void ActiveExcelApplication()
{
this.m_application = new Application();
try
{
this.m_workBook = m_application.Workbooks.Open(this.m_strFileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
this.m_totalSheets = this.m_workBook.Sheets.Count;
}
catch
{
}
}
public void ScanExcelSheetSizeByIndex(int sheetIndex)
{
Worksheet sheet = (Worksheet)m_workBook.Sheets[sheetIndex];
Range excelRange = sheet.UsedRange;
this.m_sheetColumns = excelRange.Columns.Count;
this.m_sheetRows = excelRange.Rows.Count;
this.m_activeSheet = sheetIndex;
}
public void ScanExcelSheetSizeByName(string strName)
{
for (int sheetNumber = 1; sheetNumber < m_totalSheets + 1; sheetNumber++)
{
Worksheet sheet = (Worksheet)m_workBook.Sheets[sheetNumber];
if (sheet.Name.ToLower().Equals(strName.ToLower()))
{
this.m_activeSheet = sheetNumber;
Range excelRange = sheet.UsedRange;
this.m_sheetColumns = excelRange.Columns.Count;
this.m_sheetRows = excelRange.Rows.Count;
}
}
}
public string GetCellValue(int row, int column)
{
Worksheet sheet = (Worksheet)m_workBook.Sheets[this.m_activeSheet];
string cellInfo = ((Excel.Range)sheet.Cells[row, column]).Value;
return cellInfo;
}
public void DeactiveExcelApplication()
{
try
{
this.m_workBook.Close(false, this.m_strFileName, null);
Marshal.ReleaseComObject(this.m_workBook);
}
catch
{
}
}
}
使用测试的方法,这里以一个路由整个Excel文件的所有格子内容为例来设计使用案例:
static void Main(string[] args)
{
ExcelFileReader efr = new ExcelFileReader(@"D:\work\CIMC\Parser\test.xlsx");
efr.ActiveExcelApplication();
int sheets = efr.TotalSheets;
for (int i = 1; i <= sheets; i++)
{
efr.ScanExcelSheetSizeByIndex(i);
int rows = efr.SheetRows;
int columns = efr.SheetColumns;
for (int m=1; m<=rows; m++)
{
for (int n=1; n<=columns; n++)
{
string strValue = efr.GetCellValue(m, n);
Console.WriteLine(strValue);
}
}
}
efr.DeactiveExcelApplication();
}