简体   繁体   中英

Problem Reading Excel File Having Single Quote in Sheet Name using OLEDB c#

Giving Error Invalid Character

string sSheetName="Nov'16";
dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + sSheetName+ "]", conn);
da.Fill(dt);
ds.Tables.Add(dt);

This may be of help to someone. For some reason, mine was substituting the single quote with two single quotes when I was reading in the sheet names. I ran the following and it was fixed:

                                            comm.CommandText = "Select * from [" + sheetName.Replace("''","'") + "]";

Instead of old interop you can try to use one of the modern libraries, for example ExcelDataReader

using (var stream = File.Open("C:\\Temp\\test.xlsx", FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        while (reader.Read())
        {
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var value = reader.GetValue(i)?.ToString() ?? string.Empty;
            }
        }
    }
}

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