如何通过"B7"类坐标而非行列索引访问Excel单元格并填充数据
解决方案
在C#操作Excel的Interop库中,Cells对象不直接支持通过字符串格式的单元格地址(如"B7")访问,但可以使用Range对象实现这个需求,具体修改如下:
修改核心代码
将你尝试的oSheet.Cells["B7"] = "The cell content";替换为:
oSheet.Range["B7"].Value = "The cell content";
Range对象原生支持解析Excel的单元格地址字符串,通过Value属性即可完成内容赋值,和你原来用行列索引的效果完全一致。
完整修改后的代码示例
using System.Runtime.InteropServices; // 需添加此引用用于释放COM对象 Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; try { //Start Excel and get Application object. oXL = new Excel.Application(); oXL.Visible = false; //Open existing workbook oWB = oXL.Workbooks.Open(filename); oSheet = (Excel._Worksheet)oWB.Sheets[1]; // 原行列索引方式(正常运行) oSheet.Cells[7, 2] = "The cell content"; // 新的字符串地址访问方式 oSheet.Range["B7"].Value = "The cell content"; // 批量处理目标坐标列表 string[] targetCells = {"B7", "C5", "G8"}; foreach(string cellAddr in targetCells) { oSheet.Range[cellAddr].Value = "填充内容"; } oWB.Save(); // 保存修改 oWB.Close(); } catch (Exception theException) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat(errorMessage, theException.Message); errorMessage = String.Concat(errorMessage, " Line: "); errorMessage = String.Concat(errorMessage, theException.Source); MessageBox.Show(errorMessage, "Error"); } finally { // 释放COM对象,避免Excel进程后台残留 if(oSheet != null) Marshal.ReleaseComObject(oSheet); if(oWB != null) Marshal.ReleaseComObject(oWB); if(oXL != null) { oXL.Quit(); Marshal.ReleaseComObject(oXL); } }
关键说明
Range不仅支持单个单元格地址,还支持范围格式(如"A1:C3"),后续需求扩展也能兼容。- 必须添加
System.Runtime.InteropServices引用,通过Marshal.ReleaseComObject释放COM对象,否则Excel进程会留在后台无法关闭。
内容的提问来源于stack exchange,提问作者Ron
相关产品推荐
相关产品推荐

