C#
一个整洁的最小版本,它提供了一个数据集,其中包含根据工作表命名的表(没有尾随的美元):
private static OleDbConnection GetConnection(string filename, bool openIt)
{
// if your data has no header row, change HDR=NO
var c = new OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{filename}';Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ");
if (openIt)
c.Open();
return c;
}
private static DataSet GetExcelFileAsDataSet(OleDbConnection conn)
{
var sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { default, default, default, "TABLE" });
var ds = new DataSet();
foreach (DataRow r in sheets.Rows)
ds.Tables.Add(GetExcelSheetAsDataTable(conn, r["TABLE_NAME"].ToString()));
return ds;
}
private static DataTable GetExcelSheetAsDataTable(OleDbConnection conn, string sheetName)
{
using (var da = new OleDbDataAdapter($"select * from [{sheetName}]", conn))
{
var dt = new DataTable() { TableName = sheetName.TrimEnd('$') };
da.Fill(dt);
return dt;
}
}
像这样使用它:
DataSet ds;
using(c = GetConnection(@"C:\path\to\your\xl.xlsx", true)
ds = GetExcelFileAsDataSet(c);
或者,如果您只想要一张桌子,并且您知道您想要的所有确切工作表名称(请记住,它们最后有一美元):
DataTable dt;
using(c = GetConnection(@"C:\path\to\your\xl.xlsx", true)
dt = GetExcelSheetAsDataTable(c, "Sheet1$");
VB.NET
奖金!注意:需要一个现代版本的 VB,它可以理解字符串插值、With 等内容
Private Shared Function GetConnection(filename As String, openIt As Boolean) As OleDbConnection
'if your data has no header row, change HDR=NO
Dim c = New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{filename}';Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"" ")
If openIt Then c.Open()
Return c
End Function
Private Shared Function GetExcelFileAsDataSet(conn As OleDbConnection) As DataSet
Dim sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, {Nothing, Nothing, Nothing, "TABLE"})
Dim ds = New DataSet()
For Each r As DataRow In sheets.Rows
ds.Tables.Add(GetExcelSheetAsDataTable(conn, r("TABLE_NAME").ToString()))
Next
Return ds
End Function
Private Shared Function GetExcelSheetAsDataTable(conn As OleDbConnection, sheetName As String) As DataTable
Using da = New OleDbDataAdapter($"select * from [{sheetName}]", conn)
Dim dt = New DataTable() With {.TableName = sheetName.TrimEnd("$"c)}
da.Fill(dt)
Return dt
End Using
End Function
像这样使用它:
Dim ds As DataSet
Using c = GetConnection("C:\path\to\your\xl.xlsx", True)
ds = GetExcelFileAsDataSet(c)
End Using 'closes connection
或者对于您知道其名称的单个工作表(记住工作表名称以美元结尾):
Dim dt As DataTable
Using c = GetConnection("C:\path\to\your\xl.xlsx", True)
dt = GetExcelSheetAsDataTable(c, "Sheet1$")
End Using 'closes connection