C# WebApplication - System.Data.OleDb 找到,但几乎为空



我目前正在尝试使用 OleDB 从 Excel 文件中读取。

这是代码:

using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace WebApplication1.My_Logic.Worker
{
public class ExcelLoader
{
private string GetConnectionString()
{
Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
props["Extended Properties"] = "Excel 12.0 XML";
props["Data Source"] = "C:\MyExcel.xlsx";
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
return sb.ToString();
}
private DataSet ReadExcelFile()
{
DataSet ds = new DataSet();
string connectionString = GetConnectionString();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
if (!sheetName.EndsWith("$"))
continue;
// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
return ds;
}
}
}

System.Data.OleDb显示为灰色(未使用(,并且找不到以下类:

OleDbCommand
OleDbConnection
OleDbSchemaGuid
OleDbDataAdapter

当我查看System.Data.OleDb时,Visual Studio 只显示了 2 个类:

System.Data.OleDb.OleDbPermission
System.Data.OleDb.OleDbPermissionAttribute

我在互联网上读到的任何地方,唯一的建议就是添加using System.Data.OleDb但我确实拥有它,Visual Studio似乎知道它。

它是Visual Studio 2017中新生成的 ASP.NET Core 2.1 API项目。

OleDb 在 .NET Core 中不可用,因为它不是为其他平台而不是 Windows 实现的。

请参阅以下 github 线程。

如果你想从xlsx读取,只需使用OpenXmlSdk,它是跨平台的,由.NET core支持。

请参阅如何在以下线程中使用 OpenXmlSdk 读取 excel 文件。

最新更新