如何获得Excel表格中占用的单元格的范围

我使用C#来自动化一个Excel文件。 我能够获得工作簿和它包含的工作表。 如果例如我在sheet1中有两列和五列。 我想要得到被占用的单元格的范围为A1:B5。 我试了下面的代码,但没有给出正确的结果。 列#和行#更大,单元也是空的。

Excel.Range xlRange = excelWorksheet.UsedRange; int col = xlRange.Columns.Count; int row = xlRange.Rows.Count; 

有另一种方法可以用来获得这个范围吗?

我有一个非常类似的问题,你有。 实际工作是这样的:

 iTotalColumns = xlWorkSheet.UsedRange.Columns.Count; iTotalRows = xlWorkSheet.UsedRange.Rows.Count; //These two lines do the magic. xlWorkSheet.Columns.ClearFormats(); xlWorkSheet.Rows.ClearFormats(); iTotalColumns = xlWorkSheet.UsedRange.Columns.Count; iTotalRows = xlWorkSheet.UsedRange.Rows.Count; 

恕我直言,会发生什么事是,当你从Excel中删除数据,它不断思考,这些单元格中有数据,虽然他们是空白的。 当我清除格式,它删除空白单元格,并因此返回实际的计数。

 Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range range = sheet.get_Range("A1", last); 

“范围”现在将被占用的小区范围

请参阅Range.SpecialCells方法。 例如,要获取具有常数值或公式的单元格,请使用:

 _xlWorksheet.UsedRange.SpecialCells( Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants | Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas) 

唯一的办法,我可以得到它在所有情况下工作(除保护表)(基于Farham的答案):

它支持:

  • 扫描隐藏的行/列

  • 忽略没有数据/公式的格式化单元格

码:

 // Unhide All Cells and clear formats sheet.Columns.ClearFormats(); sheet.Rows.ClearFormats(); // Detect Last used Row - Ignore cells that contains formulas that result in blank values int lastRowIgnoreFormulas = sheet.Cells.Find( "*", System.Reflection.Missing.Value, InteropExcel.XlFindLookIn.xlValues, InteropExcel.XlLookAt.xlWhole, InteropExcel.XlSearchOrder.xlByRows, InteropExcel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row; // Detect Last Used Column - Ignore cells that contains formulas that result in blank values int lastColIgnoreFormulas = sheet.Cells.Find( "*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, InteropExcel.XlSearchOrder.xlByColumns, InteropExcel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column; // Detect Last used Row / Column - Including cells that contains formulas that result in blank values int lastColIncludeFormulas = sheet.UsedRange.Columns.Count; int lastColIncludeFormulas = sheet.UsedRange.Rows.Count; 
 dim lastRow as long 'in VBA it's a long lastrow = wks.range("A65000").end(xlup).row 

现在有点旧的问题,但如果有人正在寻找解决scheme,这对我的作品。

 using Excel = Microsoft.Office.Interop.Excel; Excel.ApplicationClass excel = new Excel.ApplicationClass(); Excel.Application app = excel.Application; Excel.Range all = app.get_Range("A1:H10", Type.Missing); 

这两行本身并不为我工作:

 xlWorkSheet.Columns.ClearFormats(); xlWorkSheet.Rows.ClearFormats(); 

您可以通过在工作表中按ctrl + end并查看选定的单元格来进行testing。

我发现在前两个问题之后添加这一行解决了我遇到的所有情况下的问题:

 Excel.Range xlActiveRange = WorkSheet.UsedRange;