这几天要对一些数据格式为Excel表格的词典文进行统计,并且一些过滤。本来并不太复杂的事,由于操作Excel的关系,浪费了很长时间,下定决心要写一个操作Excel表格的类,方便以后重用。下面为代码:要添加.NET引用“using Microsoft.Office.Interop.Excel”,和对应的COM引用“Microsoft Excel 11.0 Object Library”
由于Excel的读写有较大的不同,所有把读取Excel和写入Excel分开,一以下为写入数据。
workbooks = (Excel.Workbooks)app.Workbooks;
try
{
workbooks.Open(this.FilePath, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing);
}
catch (Exception)
{
if (app != null)
{
app.Quit();
val = 1;
return val;
}
}
sheets =app.Worksheets;
worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
if (app != null)
{
app.Quit();
}
val = 1;
return val;
}
return val;
}
/// <summary>
/// 写入某个具体行列单元格数据
/// </summary>
/// <param name="row">行号,1开始</param>
/// <param name="colums">列号,1开始</param>
/// <param name="value">写入的数据</param>
/// <returns>0成功,1失败</returns>
public int WriteExcelCell(int row, int colum, string value)
{
int val = 0;
if ((row <= 0) || (colum <= 0))
{
val = 1;
return val;
}
try
{
worksheet.Cells[row, colum] = value;
}
catch(Exception )
{
val = 1;
return val;
}
return val;
}
/// <summary>
/// 清空某个单元格
/// </summary>
/// <param name="row">行</param>
/// <param name="colum">列</param>
/// <returns>0成功,1失败</returns>
public int ClearExcelCell(int row,int colum)
{
int val = 0;
if ((row <= 0) || (colum <= 0))
{
val = 1;
return val;
}
try
{
worksheet.Cells[row, colum] =string.Empty;
}
catch (Exception ex)
{
val = 1;
return val;
}
return val;
}
/// <summary>
/// 保存写入 的数据
/// </summary>
/// <returns>0成功,1失败</returns>
public int CloseAndSaveExcel()
{
int val = 0;
try
{
if (app != null)
{
app.DisplayAlerts = false;
app.UserControl = false;
}
if (worksheet != null)
{
worksheet.SaveAs(this.FilePath, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing);
}
}
catch (COMException)
{
val = 1;
return val;
}
finally
{
if (app != null)
{
app.Quit();
}
}
return val;
}
}
}