当尝试使用OLEDB从excel选择数据时,在查询表达式'Created By'中显示错误**语法错误(缺少运算符)**

时间:2019-02-01 11:54:13

标签: c# oledb

当我尝试使用OLEDB从excel中选择所有数据时,出现错误消息

查询表达式“创建者”中的语法错误(缺少运算符) 这是因为列名中有空格吗?

查询为:

  

从[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;
}

这是我尝试过的代码,这里dataExchangeSelectedColum包含它们为“代码,名称,创建者,日期”的列

2 个答案:

答案 0 :(得分:2)

如果列名包含空格,则需要在方括号名称周围添加方括号:

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

评论后编辑:

如果要选择名称可能包含空格的几列:

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

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

可以通过以下方式调用:

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

答案 1 :(得分:0)

我已经做到了

 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 += ",";
            }

        }