简体   繁体   中英

OLEDB gives an error while trying to fetch data

When I tried to select all data from excel using OLEDB.I get an error of

Syntax error (missing operator) in query expression 'Created By' Is this because of that space in the column name?

The query is:

SELECT Code,Name,Created By,Date FROM [Template$]

public DataTable GetExcelDataToTable(string filename, string dataExchangeSelectedColum)
{
    //List<DataExchangeDefinition> dataExchange = new List<DataExchangeDefinition>();
    string extension = Path.GetExtension(filename);
    string connstring = string.Empty;
    DataTable ExcelData = null;
    try
    {
        switch (extension)
        {
            case ".xls":
                connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString, filename);
                break;
            case ".xlsx":
                connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString, filename);
                break;
        }
        using (OleDbConnection connExcel = new OleDbConnection(connstring))
        {
            using (OleDbCommand cmd = new OleDbCommand())
            {
                cmd.Connection = connExcel;
                connExcel.Open();
                var dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                connExcel.Close();
                var firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                cmd.CommandText = "SELECT " + dataExchangeSelectedColum + " FROM [" + firstSheet + "]";
                ExcelData = new DataTable();
                OleDbDataAdapter oda = new OleDbDataAdapter();
                oda.SelectCommand = cmd;
                oda.Fill(ExcelData);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return ExcelData;
}

This is the code I tried, here dataExchangeSelectedColum contains the columns they are "Code, Name, Created By, Date"

You need to add square brackets around the column name if it contains spaces:

cmd.CommandText = $"SELECT [{dataExchangeSelectedColum}] FROM [{firstSheet}]";

EDIT after your comment:

If you want to select several columns which name may contain spaces:

public DataTable GetExcelDataToTable(string filename, IEnumerable<string> columns)
{
    ...
    string formattedColumns = string.Join("," columns.Select(column => $"[{column}]"));

    cmd.CommandText = $"SELECT {formattedColumns} FROM [{firstSheet}]";
    ...
}

which can be invoked the following way:

DataTable table = GetExcelDataToTable(fileName, 
    new string[] { "Code", "Name", "Created By", "Date" });

I have done it like this

 List<string> selecttedColsList = dataExchangeSelectedColum.Split(',').ToList();
        string formattedColumns = "";
        //string comma = "";
        for (int i = 0; i < selecttedColsList.Count; i++)
        {
            //formattedColumns = string.Join(",", selecttedColsList.Select(col => $"[" + selecttedColsList[i] + "]"));
            formattedColumns+= ""+$"[" + selecttedColsList[i] + "]";
            if (i != selecttedColsList.Count - 1)
            {
                formattedColumns += ",";
            }

        }            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM