【发布时间】: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;
}
【问题讨论】:
-
嗨。你看过这个例子吗? stackoverflow.com/questions/43353073/…