C# Excel 文件导入到 GridView 导致 OleDB 错误
Posted
技术标签:
【中文标题】C# Excel 文件导入到 GridView 导致 OleDB 错误【英文标题】:C# Excel file import to GridView causes OleDB Error 【发布时间】:2011-05-19 15:37:10 【问题描述】:我收到有关 OleDB 的错误。我只想将我的 excel 文件导入到 GridView。
这是我的代码。
string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;Extended Properties=Excel 8.0;HDR=YES;IMEX=1";
OleDbConnection conn = new OleDbConnection(connstr);
string strSQL = "Select * from [Sheet1$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
当我构建项目时没有错误,但是当我运行这个项目时,我得到了这样的错误:
System.ArgumentException: 的格式 初始化字符串不符合 从索引 47 开始的规范。
第 21 行:字符串 connstr = “提供者=Microsoft.Jet.Oledb.4.0;数据 源=C:\a.xls;扩展 属性=Excel 8.0;HDR=YES;IMEX=1"; 第 22 行:第 23 行: OleDbConnection 连接 = 新 OleDbConnection(connstr);
我该如何解决这个问题?
【问题讨论】:
【参考方案1】:\ 是c# string literals 中的一个特殊字符。 要在 c# 中指定字符串中的路径,请使用转义:
string path = "C:\\myFolder\\myfile.xls";
或使用逐字字符串:
string path =@"C:\myfolder\myfile.xls";
【讨论】:
【参考方案2】:您的字符串 connstr 需要为扩展属性值添加双引号。例如:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PrmPathExcelFile + @";Extended Properties=""Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text""");
【讨论】:
以上是关于C# Excel 文件导入到 GridView 导致 OleDB 错误的主要内容,如果未能解决你的问题,请参考以下文章