【问题标题】:C# Excel file import to GridView causes OleDB ErrorC# Excel 文件导入到 GridView 导致 OleDB 错误
【发布时间】: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);

我该如何解决这个问题?

【问题讨论】:

    标签: c# asp.net excel gridview oledb


    【解决方案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""");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        • 2012-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多