簡體   English   中英

嘗試打開Excel文件時出現“ Expected”

[英]“Expected )” when trying to open an excel file

我目前正在嘗試從存儲在服務器計算機上的Excel文件中檢索數據。 這是代碼。

public void ImportDataFromExcel(string excelPath)
{
  string connString ="server=D0123;uid=abc;pwd=abc@123;database=MYDB";
  string SqlTable = "xx_fields";
  string excelQuery = "Select FieldName,FieldType,Length,Decimal from [Sheet1$]";

  try {
     string excelConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelPath+";Extended Properties="+"\"Excel 12.0;HDR=Yes;IMEX=1\"";

     OleDbConnection oleDbconn = new OleDbConnection(excelConnStr);
     oleDbconn.Open(); 
     OleDbCommand oleDbcmd = new OleDbCommand(excelQuery,oleDbconn); 
     OleDbDataReader dr = oleDbcmd.ExecuteReader();
     SqlBulkCopy bulkCopy = new SqlBulkCopy(connString); 
     bulkCopy.DestinationTableName = SqlTable;

     while(dr.Read()) {
       bulkCopy.WriteToServer(dr);
     }

     oleDbconn.Close();
  } catch(Exception e) {
    Response.Write("<script>alert('Error : '" + e.Message + ");</script>");
  }
 }

但是,每次嘗試打開excel連接字符串時,我總是收到錯誤消息:“ Expected”。 我嘗試更改:

string excelConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelPath+";Extended Properties="+"\"Excel 12.0;HDR=Yes;IMEX=1\"";

string excelConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelPath+";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1""";

我的Excel文件的格式如下:

FieldName   FieldType   Length   Decimal
Name         String        10       
Date         Numeric        8        0
Address      String        40 
Age          Numeric        2        0
Price        Numeric        8        2

我仍然遇到相同的錯誤。 是什么賦予了? 最后,此C#代碼在私有引擎上運行,因此不能使用MS Visual Studio或其他庫,例如MS Office Interop。

連接字符串應為

string excelConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
excelPath + ";Extended Properties=" + "\"Excel 12.0;HDR=Yes;IMEX=1\"";

更新:

http://www.connectionstrings.com/ace-oledb-12-0/顯示了這個

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

您的excelPath應該是服務器上的物理路徑。 您可以使用Server.MapPath()獲取物理路徑。 但是,對於此函數, excelPath是參數,因此,需要在調用此函數之前確保excelPath

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM