[英]How to read and get data from excel .xlsx
我有2表的excel文件。 我需要閱讀此表並從此表中獲取所有值。 但是我所擁有的只是:
OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;");
OleDbCommand oconn = new OleDbCommand("select * from [Sheet1$]", cnn);
cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
而且我不理解為從Username和Email表中獲取所有值而需要寫的內容。 這是.xlsx表TestDb,請有人幫幫我,因為我在第二天進行谷歌搜索,我不知道該怎么做。
當我嘗試通過這種方法獲取值時,它返回一個錯誤:
var fileName = string.Format("{0}\\Include\\TestDb.xlsx", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "Username");
var data = ds.Tables["Username"].AsEnumerable();
foreach (var item in data)
{
Console.WriteLine(item);
}
Console.ReadKey();
再編輯一次:
string con =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
Console.ReadKey();
這將只讀取第一列,但是當我嘗試讀取dr [1]時,它將返回錯誤:索引超出數組的界限。
您的xlsx文件僅包含一張工作表,並且在該工作表中只有一列。 OleDb驅動程序將工作表視為數據表,並且工作表中的每一列都被視為數據列。
除了一張表(Sheet1$)
和一列(dr[0])
之外,您什么都讀不到。
如果您嘗試閱讀dr[1]
那么您將引用第二列,並且該列在Sheet1
中不存在。
只是為了測試,請嘗試在Excel文件的第二列中添加一些值。
現在您可以引用dr[1]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.