2

I am importing excel files to my application and sometimes worksheets column names have "$" sign in it. I receive this Exception:

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.

In this sheet "6um$" is a column name.

This is my code:

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();

Any ideas how to handle this situation?

Edit:

I thought the problem was having $ in column name. But turns out, The problem is having $ sign in worksheet name!

4

2 回答 2

2

好的,我找到了解决方案:由于某种原因,我重命名的工作表有额外的 $ 符号(不知道为什么,excel 中没有 $ 符号,但 OLEDB 用额外的 $ 返回它们,例如 '6um$'$ ')。我修剪第一个 $ 并使用此代码检查是否还有任何额外的 $ 符号:

char delimiterChars = '$';
string[] words = worksheetName.Split(delimiterChars);
worksheetName=words[0];
于 2013-02-14T16:05:04.793 回答
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();
            }
        }
    }
}
于 2014-02-20T14:10:20.020 回答