通过“坐标”访问 Excel 单元格的简单方法,例如“B7”而不是 [7,1]

问题描述 投票:0回答:1

我有一个 Excel 文件,我想在其中填充数据。单元格可以重新排列,并以“B7”、“C5”、“G8”等格式以列表形式给出...

所以我想通过这些协调来访问该表。

我有这个代码:

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];

    //This works good: (but need something similar)
    oSheet.Cells[7, 2] = "The cell content";

    //Need to access to cell like this:
    oSheet.Cells["B7"] = "The cell content";


    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");
}
c# excel office-interop
1个回答
0
投票

使用

Range
界面时,您可以通过地址访问单元格

// one cell
var range = oSheet.Range["B8"];
range.Value = "The cell content";

// more cells like B8, B9, C8, C9
var range = oSheet.Range["B8", "C9"];
range.Value = "The cell content";
© www.soinside.com 2019 - 2024. All rights reserved.