使用OleDB打开Excel(使用EPPLUS创建)

时间:2014-08-11 07:48:37

标签: c# excel oledb epplus

我有来自同事的代码,此代码使用Epplus创建了一些excel表。用我的代码我想添加一个数据库提取10k +/-行。由于Epplus需要太长的数据,因为您需要编写每个单元格。使用OleDB只需几秒钟。但是我不能用Epplus和OleDB打开以前创建的excel。即使使用不同的连接字符串。

如果你将两个代码块分开,我的代码就完美了。

var excelPath = "C:\\test_" + DateTime.Today.ToString("yyyyMMdd_") + DateTime.Now.ToString("hh") + DateTime.Now.Minute.ToString() + ".xlsx";
using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(excelPath)))
{
    ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Schedule V");
    worksheet.Cell(1, 1).Value = "test";
    xlPackage.Save();
    xlPackage.Dispose();
}
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml';";
using (OleDbConnection conn = new OleDbConnection(strCn))
{
    conn.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = conn;
    cmd.CommandText = "CREATE TABLE [table1] (id INT, name VARCHAR, datecol DATE );";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(1,'AAAA','2014-01-01');";
    cmd.ExecuteNonQuery();
    conn.Close();
}

我尝试了以下连接字符串,但它们都给出了同样的错误:

  

OleDbException未处理,外部表不在预期范围内   格式。

我试过的不同连接字符串:

var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 8.0;HDR=YES';";
var strCn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

我猜,它应该是这样的,而不是硬编码你应该使用OleDbConnectionStringBuilder类

OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelPath; // This is your Excel File Full Path
connectionStringBuilder.Add("Mode", "Read");

const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);

String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using (var objConn = new OleDbConnection(connectionString))
{
     // Open connection with the database.
      objConn.Open();

   // Do operations with your File here
}

答案 1 :(得分:1)

我在使用EPPlus 4.0.4创建的.xlsx文件时遇到此错误。我记得这在升级到EPPlus 4.x之前有效。我降级到3.1.3.3,我不再收到此错误。