我试图在Excel C#中访问另一个范围内的范围,并获得意外行为。在第一个范围中,Cell [1,1] .Value,按预期给出范围内第一个单元格的值。但是,在"子范围"中,Cell [1,1] .Value不会给出子范围中第一个单元格的值。相反,它会向下跳几行。
namespace RangeRange
{
class RangeRange
{
private Excel.Application excelApp = new Excel.Application();
private Excel.Workbook workbook;
private Excel.Worksheet worksheet;
public int Load(string filepath)
{
workbook = excelApp.Workbooks.Open(filepath);
worksheet = (Excel.Worksheet)workbook.Sheets[1];
return 0;
}
public int Close()
{
// Shut down excel.exe
workbook.Close();
excelApp.Quit();
return 0;
}
public int Process()
{
Excel.Range data_range = worksheet.UsedRange.Cells;
int rows = data_range.Rows.Count;
int cols = data_range.Columns.Count;
// Get the range containing rows 3 through N.
Excel.Range c1 = worksheet.Cells[3, 1];
Excel.Range c2 = worksheet.Cells[rows, cols];
Excel.Range range1 = (Excel.Range)worksheet.get_Range(c1, c2);
string value1 = range1.Cells[1, 1].Value;
Console.WriteLine(value1);
ProcessRange(range1);
return 0;
}
private int ProcessRange(Excel.Range my_range)
{
// Get a range, containing all rows, within my_range.
int rows = my_range.Rows.Count;
int cols = my_range.Columns.Count;
Excel.Range c1 = my_range.Cells[1, 1];
Excel.Range c2 = my_range.Cells[rows, cols];
Excel.Range range2 = (Excel.Range)my_range.get_Range(c1, c2);
string value2 = range2.Cells[1, 1].Value;
Console.WriteLine(value2);
return 0;
}
}
}
我的输入数据是:
输出结果为:
答案 0 :(得分:0)
通过从传入的范围中获取工作表,然后将所需的"子范围"设置为工作表上的范围,我能够使其正常工作。
private int ProcessRange(Excel.Range my_range)
{
// Get a range, containing all rows, within my_range.
int rows = my_range.Rows.Count;
int cols = my_range.Columns.Count;
Excel.Range c1 = my_range.Cells[1, 1];
Excel.Range c2 = my_range.Cells[rows, cols];
Excel.Worksheet ws = my_range.Worksheet;
Excel.Range range2 = (Excel.Range)ws.Range[c1, c2];
string value2 = range2.Cells[1, 1].Value;
Console.WriteLine(value2);
return 0;
}