C# Excel的读取和修改
public void ReadExcelAndModify(string strFileFullName)
{
int IDX = 1;
int TestcaseName = 3;
int Result = 5;
//读取Excel文件
Microsoft.Office.Interop.Excel.Application objExcelApp;//定义Excel Application对象
Microsoft.Office.Interop.Excel.Workbooks objExcelWorkBooks;//定义Workbook工作簿集合对象
Microsoft.Office.Interop.Excel.Workbook objExcelWorkbook;//定义Excel workbook工作簿对象
Microsoft.Office.Interop.Excel.Worksheet objExcelWorkSheet;//定义Workbook工作表对象
object oMissiong = System.Reflection.Missing.Value;
objExcelApp = new Microsoft.Office.Interop.Excel.Application(); objExcelWorkBooks = objExcelApp.Workbooks;
objExcelWorkbook = objExcelWorkBooks.Open(strFileFullName, 0, false, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//打开工作表
objExcelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)objExcelWorkbook.Worksheets[1]; //strSheetName是指的Exce工作簿的Sheet名,如果没有命名则为"1"
objExcelWorkSheet.Select(Type.Missing);
try
{
DataTable dt = new DataTable();
int iRowCount = objExcelWorkSheet.UsedRange.Rows.Count;
int iColCount = objExcelWorkSheet.UsedRange.Columns.Count;
for (int i = 2; i < iRowCount; i++)
{
string strIDX = ((Microsoft.Office.Interop.Excel.Range)objExcelWorkSheet.Cells[i, IDX]).Text.ToString();
if (strIDX == "√")
{
string strTestcaseName = ((Microsoft.Office.Interop.Excel.Range)objExcelWorkSheet.Cells[i, TestcaseName]).Text.ToString();
object result = CaseInstance.GetType().GetMethod(strTestcaseName).Invoke(CaseInstance, null);
if (result != null)
{
//textResult.Text += String.Format(result.ToString());
objExcelWorkSheet.Cells[i, Result] = result;
}
}
}
objExcelWorkbook.Save();
}
catch (Exception)
{
throw;
}
finally
{
objExcelWorkbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcelWorkbook);
objExcelWorkbook = null;
objExcelApp.Workbooks.Close();
objExcelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcelApp);
objExcelApp = null;
}
}