获取正在使用的Excel电子表格范围的标准方法是使用UsedRange方法。我可以像这样复制所有已使用的单元格:
xlWorkSheet.UsedRange.Copy(misValue);
很不幸,这不是一个好方法,因为如果用户在单元格中输入并再次删除,则会“激活”单元格。这可能会意外地导致标记数千个空行和列(在我的情况下打印出来)。
因此,我已经将此方法翻译成C#,以获得更准确的范围。调试时,它给出了FirstRow = 1,FirstColumn = 1,LastRow = 600,LastColumn = 2,这正是我想要使用测试工作表作为输入。
但我仍然需要设置实际使用的范围并复制它。在VB中,可以这样做:
Set RealUsedRange = Range(Cells(FirstRow, FirstColumn), Cells(LastRow, LastColumn))
我该如何在C#中设置范围并进行复制?我想替换这行代码:
xlWorkSheet.UsedRange.Copy(misValue);
针对范围为(1,1)至(600,2)的情况,我尝试了以下方法:
return Excel.Range(xlWorkSheet.Cells[FirstRow, FirstColumn], xlWorkSheet.Cells[LastRow, LastColumn]);
但它给出了 Excel.Range 是一个“类型”,这在给定的上下文中是无效的。我不知道正确的写法。
// this struct is just to make the result more readable
public struct RealRange
{
public int FirstRow;
public int FirstColumn;
public int LastRow;
public int LastColumn;
public RealRange(int fr, int fc, int lr, int lc)
{
FirstRow = fr;
FirstColumn = fc;
LastRow = lr;
LastColumn = lc;
}
}
public RealRange RealUsedRange()
{
int FirstRow = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.get_Range("IV65536", misValue),
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlNext,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value
).Row;
int FirstColumn = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.get_Range("IV65536", misValue),
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByColumns,
Excel.XlSearchDirection.xlNext,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value
).Column;
int LastRow = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.get_Range("IV65536", misValue),
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlPrevious,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value
).Row;
int LastColumn = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.get_Range("IV65536", misValue),
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByColumns,
Excel.XlSearchDirection.xlPrevious,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value
).Column;
return new RealRange(FirstRow, FirstColumn, LastRow, LastColumn);
}
解决方案 注意,我已将返回值从void更改为RealRange结构体。这是为了使结果更容易阅读。“范围”是电子表格中两个单元格之间的跨度。您可以使用get_range函数来复制范围,就像我下面所做的那样。感谢D.Hilgarth的帮助。
rr = RealUsedRange();
this.workSheet.get_Range(
this.workSheet.Cells[rr.FirstRow, rr.FirstColumn],
this.workSheet.Cells[rr.LastRow, rr.LastColumn]).Copy(missing);