【问题标题】:C# and Reading Excel Data: Rows.Count is 0 despite having data in my excel fileC# 和读取 Excel 数据:尽管我的 excel 文件中有数据,但 Rows.Count 为 0
【发布时间】:2019-06-13 15:37:43
【问题描述】:

我正在尝试从 excel 文件中读取数据并将其存储在二维数组中。但是,尽管我的 excel 工作表中有数据,但我在 excel 工作表上调用的函数似乎返回 0,例如行/列计数。我必须对我的 Excel 表进行某种格式设置吗?

例如,当我在xlSheet 的一般范围而不是使用范围上调用计数行函数时,由于某种原因它返回 0。

public static String[,] ReadExcelData(string fileName, string sheet)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
            Excel.Worksheet xlSheet = (Excel.Worksheet)xlWorkbook.Sheets[sheet];
            Excel.Range range = xlSheet.UsedRange;

            int rowCount = range.Rows.Count;
            int columnCount = range.Columns.Count;
            String[,] dataArray = new String[rowCount, columnCount];

            for (int currColumn = 1; currColumn <= columnCount; currColumn++)
            {
                for (int currRow = 1; currRow <= rowCount; currRow++)
                {
                    if (range.Cells[currRow, currColumn] == null || range.Cells[currRow, currColumn].ToString() == "n/a")
                    {
                        dataArray[currRow - 1, currColumn - 1] = "";
                    }
                    else
                    {
                        dataArray[currRow - 1, currColumn - 1] = range.Cells[currRow, currColumn].ToString();
                    }
                }
            }
            xlWorkbook.Close();
            return dataArray;
        }

【问题讨论】:

标签: c# excel


【解决方案1】:

如果您只想读取数据,我推荐 ExcelDataReader。

ExcelDataReader 示例:https://csharp.hotexamples.com/examples/-/ExcelDataReader/-/php-exceldatareader-class-examples.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多