将C#4连接到excel 2007(excel 12.0库) [英] Connecting C# 4 to excel 2007 (excel 12.0 library)
问题描述
我正在尝试从C#4.0连接到Excel 12.0.我使用以下代码.
Hi,
I am trying to connect to excel 12.0 from c# 4.0. I use the following code.
string excelConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + txtFile.Text +
"; Extended Properties=Excel 12.0; HDR=yes;IMEX=1;ImportMixedTypes=Text";
DataTable table = new DataTable();
using (OleDbConnection oledbConn = new OleDbConnection(excelConnection)) {
oledbConn.Open();
using (OleDbCommand command = new OleDbCommand("Select * from [Sheet1$]", oledbConn)) {
OleDbDataReader reader = command.ExecuteReader();
table.Load(reader);
}
}
它编译良好.但是在运行时,它会产生错误-未处理OleDbException-找不到可安装的ISAM.请帮助.
It is compiling good. But in runtime, it produces the error - OleDbException unhandled - Could not find installable ISAM. Please help.
推荐答案
,oledbConn)){ OleDbDataReader reader = command.ExecuteReader(); table.Load(阅读器); } }
", oledbConn)) { OleDbDataReader reader = command.ExecuteReader(); table.Load(reader); } }
它编译良好.但是在运行时,它会产生错误-未处理OleDbException-找不到可安装的ISAM.请帮忙.
It is compiling good. But in runtime, it produces the error - OleDbException unhandled - Could not find installable ISAM. Please help.
在使用Microsoft工具(混合使用64位计算机)时,我遇到了很多问题,还有其他问题.使用此工具 http://exceldatareader.codeplex.com/
,我取得了很大的成功
使用此工具获取数据集的示例(每张工作表一个表):
I''ve had a lot of problems using the Microsoft tools with the mix of 64 bit machines out there and other issues. I have had a lot of great success with this tool http://exceldatareader.codeplex.com/
Example to get the dataset using this tool (a table for every sheet):
DataSet output = new DataSet();
using (FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
Excel.IExcelDataReader excelReader = fileName.IndexOf(".xlsx") > -1 ? Excel.ExcelReaderFactory.CreateOpenXmlReader(stream) :
Excel.ExcelReaderFactory.CreateBinaryReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
output = excelReader.AsDataSet(false);
}
只需进行一些简单的错误检查,您就可以使用此工具,它可以同时处理旧版本的Excel和新版本.
Some simply error checking and you are on your way, this tool handles both older versions of Excel and the newer versions.
这篇关于将C#4连接到excel 2007(excel 12.0库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!