How do I get an entire column in used range?

后端 未结 3 1932
花落未央
花落未央 2020-12-11 01:46

I am trying to get a column, but limiting it to used range...

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


        
相关标签:
3条回答
  • 2020-12-11 02:13

    You can use

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

    or this

    sheet.UsedRange.Columns["F:F", Type.Missing].Rows.Count
    
    0 讨论(0)
  • 2020-12-11 02:17

    this is the optimized way to read an Excel file column by column (or row by row) :

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-11 02:24

    Sounds like you want the Application.Intersect of the UsedRange and Column("F:F")

    0 讨论(0)
提交回复
热议问题