我目前正在嘗試從我的 C# 代碼中的 Excel 檔案訪問資料。那是我的嘗試:
public static void Main(string[] args)
{
var filepath= ".../0f351ee0-0e7b-488b-80c5-db5da81f4bb5.xlsx";
ReadExcel(file_path, ".xlsx");
Console.ReadLine();
}
enter code here
public static DataTable ReadExcel(string fileName, string fileExt)
{
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xls") == 0)
conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" fileName ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" fileName ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch { }
}
Console.WriteLine(dtexcel);
return dtexcel;
問題是 DataTable 總是空的。我究竟在哪里可以解決這個問題?
uj5u.com熱心網友回復:
雖然 JET/Access 驅動程式可以像讀取資料庫一樣讀取 Excel 檔案,但它有幾個問題,尤其是在 .NET Core 時代:
- 僅限 Windows
- 它需要安裝。它不能與您的應用程式打包在一起
- 安裝的版本必須與任何 Office 組件的位數(32/64 位)匹配。這反過來意味著您的應用程式必須與 Office 的位數相匹配。
有些庫可以直接讀取 Excel 檔案。一個這樣的選項是ExcelDataReaderDbDataReader ,它在 Excel 作業表上打開一個。它可以處理過時的xls格式和 16 年前的xlsx格式(是的,“新”xlsx 格式是在 16 年前的 2006 年引入的)。
生成的資料讀取器可用于讀取資料或加載與任何其他資料讀取器相同的 DataTable。
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var table=new DataTable();
table.Load(reader);
...
}
}
ExcelDataReader 有一個擴展,允許將作業簿中的所有作業表讀入資料集中,每個作業表都有一個資料表。
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var dataset= reader.AsDataSet();
// The result of each spreadsheet is in dataset.Tables
}
}
uj5u.com熱心網友回復:
這就是我從 Excel 檔案中讀取的方式:
public static DataSet Import(string path)
{
var dataStructure = new DataSet();
// Create the connection string and connect to the excel table by OleDbConnection.
string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={path};Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
using (var conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
}
catch (Exception e)
{
MessageBox.Show($"Cannot connect to the OLEDB (Excel) driver with the connection string \"{connectionString}\".\n{e}");
return null;
}
DataTable sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (OleDbCommand cmd = conn.CreateCommand())
{
foreach (DataRow row in sheets.Rows)
{
var tableName = row["TABLE_NAME"].ToString();
string sql = $"SELECT * FROM [{tableName}]";
var oleDbDataAdapter = new OleDbDataAdapter(sql, conn);
oleDbDataAdapter.Fill(dataStructure, tableName);
}
}
conn.Close();
}
return dataStructure;
}
我強烈建議您使用 Open-XML-SDK 來讀取 Excel 檔案: Open-XML-SDK nuget 這將使生活更輕松一些。例如:
SpreadsheetDocument.Open(fileName, isEditable);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/425683.html
上一篇:抽象類實作設計
