C# Excel 文件导入到 GridView 导致 OleDB 错误

发布于 2024-10-05 14:54:06 字数 821 浏览 0 评论 0原文

我收到有关 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 conn = 新 OleDbConnection(connstr);

我该如何解决这个问题?

I got an error about OleDB. I just want my excel file import to GridView.

Here is my code.

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();

When I build project there is no error, but when I run this project, I got an error like this:

System.ArgumentException:Format of the
initialization string does not conform
to specification starting at index 47.

Line 21: string connstr =
"Provider=Microsoft.Jet.Oledb.4.0;Data
Source=C:\a.xls;Extended
Properties=Excel 8.0;HDR=YES;IMEX=1";
Line 22: Line 23:
OleDbConnection conn = new
OleDbConnection(connstr);

How can I fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

把时间冻结 2024-10-12 14:54:06

\ 是 c# 字符串文字 中的特殊字符。
要在 C# 中的字符串中指定路径,请使用转义:

string path = "C:\\myFolder\\myfile.xls";

或使用逐字字符串:

string path =@"C:\myfolder\myfile.xls";

\ is a special char in c# string literals.
To specify paths in a string in c# either use escaping:

string path = "C:\\myFolder\\myfile.xls";

or use verbatim strings:

string path =@"C:\myfolder\myfile.xls";
拥抱我好吗 2024-10-12 14:54:06

您的字符串 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""");

Your string connstr needs double quotes for the Extended Properties values. e.g.:

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""");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文