如何在使用范围内获得整列?

时间:2011-03-23 20:41:39

标签: c# excel interop

我正在尝试获取一个列,但将其限制为使用范围...

public static Excel.Application App = new Excel.Application();
public static Excel.Workbook WB;

WB = App.Workbooks.Open("xxx.xls", ReadOnly: true);

var sheet = (WB.Sheets[1] as Excel.Worksheet);

// returns 65536 rows, I want only 82 (used range)
sheet.get_Range("F:F");

sheet.UsedRange.get_Range("F:F").Rows.Count; // 65536

我怎样才能得到它?

3 个答案:

答案 0 :(得分:18)

您可以使用

sheet.UsedRange.Columns[6, Type.Missing].Rows.Count

或者

sheet.UsedRange.Columns["F:F", Type.Missing].Rows.Count

答案 1 :(得分:3)

听起来你想要UsedRange和Column的Application.Intersect(“F:F”)

答案 2 :(得分:3)

这是逐列(或逐行)读取Excel文件的优化方法:

static void ReadExcelFile(filename) {
   Excel.Application xlApp = new Excel.Application();
   Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
   Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); // 1st sheet
   // the entire table :
   Excel.Range range = xlWorkSheet.UsedRange; // range.Rows.Count, range.Columns.Count

   for (int col = 1; col <= range.Columns.Count; col++) {
        // this line does only one COM interop call for the whole column
        object[,] currentColumn = (object[,])range.Columns[col, Type.Missing].Value; 
        double sum = 0;
        for (int i = 1; i < currentColumn.Length; i++) {
             object val = currentColumn[i, 1];
             sum += (double)val; // only if you know that the values are numbers 
             // if it was a string column :
             //Console.WriteLine("{0}",(string)val);
        }
    }
}