获取 DataTable 中的 Excel 条数据
Get Excel data in DataTable
我目前正尝试在我的 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 总是空的。我在哪里可以解决这个问题?
这是我从 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);
虽然 JET/Access 驱动程序可以像读取数据库一样读取 Excel 文件,但它有几个问题,尤其是在 .NET Core 时代:
- 是Windows-only
- 需要安装。它不能与您的应用程序打包
- 安装的版本必须与任何 Office 组件的位数(32/64 位)匹配。这反过来意味着 您的 应用程序必须匹配 Office 的位数。
有些库可以直接读取 Excel 文件。一个这样的选项是 ExcelDataReader,它在 Excel sheet 上打开 DbDataReader
。它可以处理过时的 xls
格式和 16 年前的 xlsx
格式(是的,“新”xlsx 格式是在 16 年前的 2006 年引入的)。
生成的数据reader可用于读取数据或加载数据表,与任何其他数据相同reader。
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var table=new DataTable();
table.Load(reader);
...
}
}
ExcelDataReader 有一个扩展,允许将工作簿中的 所有 sheet 读取到 DataSet 中,每个 sheet.
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
}
}
我目前正尝试在我的 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 总是空的。我在哪里可以解决这个问题?
这是我从 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);
虽然 JET/Access 驱动程序可以像读取数据库一样读取 Excel 文件,但它有几个问题,尤其是在 .NET Core 时代:
- 是Windows-only
- 需要安装。它不能与您的应用程序打包
- 安装的版本必须与任何 Office 组件的位数(32/64 位)匹配。这反过来意味着 您的 应用程序必须匹配 Office 的位数。
有些库可以直接读取 Excel 文件。一个这样的选项是 ExcelDataReader,它在 Excel sheet 上打开 DbDataReader
。它可以处理过时的 xls
格式和 16 年前的 xlsx
格式(是的,“新”xlsx 格式是在 16 年前的 2006 年引入的)。
生成的数据reader可用于读取数据或加载数据表,与任何其他数据相同reader。
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var table=new DataTable();
table.Load(reader);
...
}
}
ExcelDataReader 有一个扩展,允许将工作簿中的 所有 sheet 读取到 DataSet 中,每个 sheet.
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
}
}