我正在使用下面的代码阅读我的Excel电子表格(Sample.xls,也在下面)。
Sample.xls
[Sheet 1]
第0列,第0行=“测试1”
第0列,第1行=“测试2”
第0列,第2行=“测试3”
[第2页] 所有列/行都是空白的
public void importFileButton_Click(object sender, EventArgs e)
{
string sourcefile = "C:\\Sample.xls";
string sqlQuery = null;
if (File.Exists(sourceFile))
{
DataTable fileSheetInfo = null;
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"");
connection.Open();
fileSheetInfo = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int fileSheetCount = fileSheetInfo.Rows.Count;
OleDbCommand command = new OleDbCommand();
String[] sheetNames = new String[fileSheetInfo.Rows.Count];
int i = 0;
foreach (DataRow row in fileSheetInfo.Rows)
{
sheetNames[i] = row["TABLE_NAME"].ToString();
sqlQuery1 = "SELECT * FROM [" + sheetNames[i] + "]";
command.CommandText = sqlQuery1;
OleDbDataAdapter adapter1 = new OleDbDataAdapter(sqlQuery, connection);
DataTable sheetData = new DataTable();
adapter1.Fill(sheetData);
int iRow = sheetData.Rows.Count;
MessageBox.Show("Sheet Name: " + sheetNames[i], "Sheet Name", MessageBoxButtons.OK);
MessageBox.Show("Rows: " + iRow.ToString(), "Row Count", MessageBoxButtons.OK);
i++;
}
}
}
为什么代码会为空白工作表(Sheet2)返回1或2的行数?为什么第2页的行数显示为0?我注意到如果我在Excel中打开文件,则rowcount为1; 2如果文件在Excel中关闭。
感谢您的帮助!