使用Microsoft.Office.Interop.Excel读取所有行和列 [英] Read All Rows and Columns Using Microsoft.Office.Interop.Excel

查看:1150
本文介绍了使用Microsoft.Office.Interop.Excel读取所有行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4列4行的Excel工作表.当我读取带有Microsoft.Office.Interop.Excel.WorkSheet的列和行Count时,行和列16384的行和列计数为1048576.行和列的计数必须为4.我想念什么?

I have excel sheet with 4 columns and 4 rows. When I read the columns and rows Count with Microsoft.Office.Interop.Excel.WorkSheet the count of rows and columns are 1048576 for rows and for columns 16384. The count must be 4 for rows and 4 for columns. What did I miss ?

            ApplicationClass excelApp = null;
            Workbook myWorkBook = null;
            Worksheet mySheet = null;
            Range dataRange = null;
            excelApp = new ApplicationClass();
            myWorkBook = excelApp.Workbooks.Open(@"C:\Users\Dev2Admin\Desktop\Employees.xlsx");
            mySheet = (Worksheet)myWorkBook.Sheets["Sheet1"];


            for (int row = 1; row < mySheet.Rows.Count; row++) // Count is 1048576 instead of 4
            {
                for (int col = 1; col < mySheet.Columns.Count; col++) // Count is 16384 instead of 4
                {
                    dataRange = (Range)mySheet.Cells[row, col];
                    Console.Write(String.Format(dataRange.Value2.ToString() + " "));
                }
                Console.WriteLine();
            }

推荐答案

您已经省略了UsedRange属性,即您在工作表上使用的正确列数或行数,如下所示:

You have omitted UsedRange property, the correct used column or row count on your sheet you get like this:

  int totalColumns = mySheet.UsedRange.Columns.Count;
  int totalRows = mySheet.UsedRange.Rows.Count;

这篇关于使用Microsoft.Office.Interop.Excel读取所有行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆