我正在尝试在excel中读取excel文件,但由于某种原因,有时会丢失第一列,并且数据中缺少第一行。
当我在excel中打开文件并保存而不进行任何更改时,文件将被正确读取。
关于如何发生这种情况的任何想法?
以下是我用来阅读文件的代码:
string xlConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source="
+ txt_InputFile.Text
+ ";Extended Properties=Excel 8.0;";
using (OleDbConnection dbConnection = new OleDbConnection(xlConn))
{
dbConnection.Open();
// Get the name of the first worksheet:
DataTable dbSchema = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
//"Error: Could not determine the name of the first worksheet."
throw new Exception(Program.lm_GetMethodLanguage(this.GetType().Name, "wp_InputFile_CloseFromNext", 5) );
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
using (
OleDbDataAdapter dbCommand = new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]",
dbConnection))
{
using (DataSet myDataSet = new DataSet())
{
dbCommand.Fill(myDataSet);
inputData = myDataSet.Tables[0];
}
}
}
答案 0 :(得分:-1)
使用此功能。这将检索Excel工作表中的所有工作表。
private String[] GetExcelSheetNames(string excelFile)
{
try
{
excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ""yoursourcepath"+ ";Extended Properties=Excel 12.0;Persist Security Info=False";
excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
if (excelConnection != null)
{
excelConnection.Close();
excelConnection.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}