第一步,添加引用
Microsoft.Office.Interop.Excel
第二步,调用函数
/// <summary> /// 向excel中指定sheet指定位写入数据 /// </summary> /// <param name="fileName">excel文件名,带路径</param> /// <param name="sheetName">表单名称</param> /// <param name="lineNbr">指令行数,从1开始</param> /// <param name="dt">修改值</param> /// <param name="mylog">记录日志,用于错误输出</param> public static void WriteToEcel(string fileName, string sheetName, int lineNbr, string dt, log4net.ILog mylog) { 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工作表对象 objExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); objExcelWorkBooks = objExcelApp.Workbooks; try { objExcelWorkbook = objExcelWorkBooks.Open(fileName, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); objExcelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)objExcelWorkbook.Worksheets[sheetName]; //strSheetName是指的Exce工作簿的Sheet名,如果没有命名则为"1" objExcelWorkSheet.Select(Type.Missing); Microsoft.Office.Interop.Excel.Worksheet objExcelWorkSheetTemp = (Microsoft.Office.Interop.Excel.Worksheet)objExcelApp.ActiveSheet; //在指令行列中写入数据 objExcelWorkSheetTemp.Cells[lineNbr, 2] = dt; objExcelWorkbook.Save(); objExcelWorkbook.Close(); } catch (Exception ex) { mylog.Error(ex.Message); } }
此方法很慢,很慢