【发布时间】:2011-05-30 08:15:03
【问题描述】:
获取正在使用的 Excel 电子表格范围的标准方法是 UsedRange 方法。我可以像这样复制所有使用过的单元格:
xlWorkSheet.UsedRange.Copy(misValue);
不幸的是,这不是一个好方法,因为如果用户在一个单元格中写入一些内容然后再次删除它,则单元格会被“激活”。它可能会产生无意的后果,即标记了数千个空行和列(在我的例子中是打印出来的)。
所以我将this 方法翻译成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 更改为 struct 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);
【问题讨论】:
-
不要编辑答案,用解决方案编辑你自己的问题,由丹尼尔编辑他自己的答案..
-
他几乎找到了解决办法。我将其添加到我的原始答案中。
-
干杯,这就是你应该这样做的方式。您可以评论他的答案,以便他也可以看到您的解决方案。