使用 Oledb 导出到 excel(xlsx)

Export to excel(xlsx) using Oledb

有没有办法在不使用任何第三方库的情况下使用 ADO 将数据导出到 excel(xslx)。Net/Oledb?

如果您在 Google 上搜索一下,有很多方法可以做到这一点。

https://www.aspsnippets.com/Articles/Export-Data-to-Excel-Sheet-using-ADO.Net-and-C.aspx

http://diegworld.blogspot.com/2010/09/importexport-dataset-to-excel-file-with.html

这是工作代码... 首先,您需要在 webconfig 文件中添加以下连接字符串

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
    <add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />

然后在你后面的代码中应用这段代码

            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT NAME,ADDRESS FROM TBL_STUDENT", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd );
            DataSet DT = new DataSet();
            da.Fill(DT );                           
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = DT.Tables[0];
            GridView1.DataBind();
            con.Close();
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename=StudentsData_" + System.DateTime.Now + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }


            GridView1.RenderControl(hw);
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();