![](https://csdnimg.cn/release/download_crawler_static/87651884/bg1.jpg)
C#读 Excel 时如果 sheet 名不对报错的解决方案
'Sheet1$' 不是一个有效名称。请确认它不包含无效的字符或标点,
且名称不太长。 2009-10-27 12:06 如果大家在 google 搜 C#读取
excel 数据,一定会搜索出一下的代码:
public DataTable ExcelToDS(string Path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = null;
DataTable dt = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
dt = new DataTable();
但是上面的代码只是查询 sheet1$表,如果用户把 sheet 表名改
了就是报下面的错:
'sheet1$' 不是一个有效名称。请确认它不包含无效的字符或标点,
且名称不太长。
那么怎样才能获得 Excel 中各个 sheet 的名称呢?这样就能动态的
选中返回那个 sheet 的数据,即使用户更改了名称也不怕,完全可以
把所有 sheet 的名称列出来供用户选择: