如何在 ASP.NET 中执行导入导出到 Excel 功能?

发布于 2024-11-09 02:27:17 字数 71 浏览 0 评论 0原文

在我的 ASP.NET Web 应用程序中,有一个要求,我必须将数据导入到 Excel 或从 Excel 导出数据。我该怎么做?

In my asp.net web application there is a requirement where i have to import and export data to and from an excel. how can i do it?

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

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

发布评论

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

评论(1

め七分饶幸 2024-11-16 02:27:17

这是在 Excel 中导出数据的代码

StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    string attachment = "attachment; filename=excel" + ".xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    rptMain.DataBind();
    rptMain.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.Flush();
    Response.End();

,这是从 Excel 导入数据的代码

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        DbDataAdapter adapter = factory.CreateDataAdapter();
        DbCommand selectCommand = factory.CreateCommand();
        selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;
        selectCommand.Connection = connection;
        adapter.SelectCommand = selectCommand;
        DataTable dtbl = new DataTable();
        adapter.Fill(dtbl);

        if (dtbl.Rows.Count > 0)
        {
         .............
         .............
        }

here is code to export data in excel

StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    string attachment = "attachment; filename=excel" + ".xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    rptMain.DataBind();
    rptMain.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.Flush();
    Response.End();

and here is code to import Data from Excel

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        DbDataAdapter adapter = factory.CreateDataAdapter();
        DbCommand selectCommand = factory.CreateCommand();
        selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;
        selectCommand.Connection = connection;
        adapter.SelectCommand = selectCommand;
        DataTable dtbl = new DataTable();
        adapter.Fill(dtbl);

        if (dtbl.Rows.Count > 0)
        {
         .............
         .............
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文