这里有一个类似的问题 In Memory OleDbConnection to Excel File 但是,通过另一种方式完全避免它来回答这个问题。
下面是一些示例代码,它使用 OleDbConnection
从磁盘访问 Excel 文件:
static void Main(string[] args)
{
String filePathToExcelFile = "c:excelfile.xls";
Boolean hasHeaders = true;
String connectionString = String.Format(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};" +
"Extended Properties="Excel 12.0;HDR={1};IMEX=2"",
filePathToExcelFile, hasHeaders ? "Yes" : "No");
using(OleDbConnection conn = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]",
conn))
{
conn.Open();
OleDbDataReader datareader = command.ExecuteReader();
while(datareader.Read())
{
Object[] values = new object[datareader.FieldCount];
datareader.GetValues(values);
Console.WriteLine(String.Join(",", values));
}
}
}
我想从 NON-SEEKABLE System.IO.Stream
中提取 Excel 文件,而不是磁盘上的持久文件。
问题分为两部分,a)我可以将 OleDbConnection 指向 System.IO.Stream 吗? b)如果是这样,那可以是仅向前的流而不是可搜索的流吗?
仅供参考:如果你想运行这个代码片段,你需要安装 Microsoft Access Database Engine 2010 Redistributable 。如果您安装 64 位,则需要将项目定位为 x64,反之亦然。
如果有帮助,请检查: http://epplus.codeplex.com/
还有示例代码: