问题描述
|
获取使用中的电子表格范围的标准方法是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是一个\'type \',在给定的上下文中无效。我不知道编写它的正确方法。
// 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
).Row;
int FirstColumn = xlWorkSheet.Cells.Find(
\"*\",Excel.XlSearchOrder.xlByColumns,System.Reflection.Missing.Value
).Column;
int LastRow = xlWorkSheet.Cells.Find(
\"*\",Excel.XlSearchDirection.xlPrevIoUs,System.Reflection.Missing.Value
).Row;
int LastColumn = xlWorkSheet.Cells.Find(
\"*\",System.Reflection.Missing.Value
).Column;
return new RealRange(FirstRow,FirstColumn,LastRow,LastColumn);
}
解
注意,我已将返回值从void更改为结构RealRange。这是为了使结果更具可读性。电子表格中的“范围”是2个单元格之间的范围。您可以像下面一样使用get_range-function复制范围。谢谢D. Hilgarth的帮助。
rr = RealUsedRange();
this.workSheet.get_Range(
this.workSheet.Cells[rr.FirstRow,rr.FirstColumn],this.workSheet.Cells[rr.LastRow,rr.LastColumn]).copy(missing);
解决方法
我认为您想要
RealUsedRange
返回类型为Range
的对象,就像原始函数一样。
像这样:
public Range RealUsedRange()
{
// ...
return xlWorkSheet.get_Range(xlWorkSheet.Cells[FirstRow,FirstColumn],xlWorkSheet.Cells[LastRow,LastColumn]);
}