2013-02-14 50 views
2

我正在將excel文件導入到我的應用程序中,有時工作表列名中有「$」符號。我收到此例外情況:如何處理OleDb Excel導入中的無效字符?

System.Data.OleDb.OleDbException was unhandled 
Message=''6um$'$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long. 

在此表中,「6um $」是列名稱。

這是我的代碼:

OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString); 
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
    "select * from [" + worksheetName + "$]", con); 

con.Open(); 
System.Data.DataSet excelDataSet = new DataSet(); 
cmd.Fill(excelDataSet); 
con.Close(); 

任何想法如何處理這種情況?

編輯:

我認爲這個問題是在列名有$。但事實證明,問題是工作表名稱中有$符號!

+0

這是一個猜測,所以我不把作爲一個答案。嘗試在有問題的列名稱周圍放置單引號或雙引號或括號[],並刪除「*」。 ex從[Sheet1 $]中選擇[$ omeColumn],ColB,ColC。 – granadaCoder 2013-02-14 15:29:59

回答

2

好的,我想出瞭解決方案: 出於某種原因,我重命名我自己的工作表有額外的$符號(不知道爲什麼,沒有$符號在Excel中,但OLEDB返回它們與額外的$這樣的東西'6um $' $「)。我修剪第一$關閉,並使用此代碼來檢查是否有是還留有額外的$符號:

char delimiterChars = '$'; 
string[] words = worksheetName.Split(delimiterChars); 
worksheetName=words[0]; 
0
if (Directory.Exists(serverPath)) 
{ 
    string FileExist = sp + "book1.xlsx"; ; 
    string Exten = Path.GetExtension(FileExist); 
    string g = "sheet1";    

    if (File.Exists(FileExist)) 
    { 
     if (Exten == ".xlsx") 
     { 
      string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileExist + ";Extended Properties=Excel 12.0"; 

      OleDbConnection oledbConn = new OleDbConnection(connString); 
      try 
      { 
       // Open connection 
       oledbConn.Open(); 
       string query = String.Format("select * from [{0}$]", g); 

       // Create OleDbCommand object and select data from worksheet Sheet1 
       OleDbCommand cmd = new OleDbCommand(query, oledbConn); 

       // Create new OleDbDataAdapter 
       OleDbDataAdapter oleda = new OleDbDataAdapter(); 

       oleda.SelectCommand = cmd; 

       // Create a DataSet which will hold the data extracted from the worksheet. 
       DataSet ds = new DataSet(); 

       // Fill the DataSet from the data extracted from the worksheet. 
       oleda.Fill(ds, "sheetdt");        

       GridView1.DataSource = ds.Tables[0].DefaultView; 
       GridView1.DataBind(); 
      } 
      catch (Exception ex) 
      { 
       LblSuccess.Text = ex.Message; 
      } 
      finally 
      { 
       // Close connection 
       oledbConn.Close(); 
      } 
     } 
    } 
}