繁体   English   中英

使用Oledb导出到excel(xlsx)

[英]Export to excel(xlsx) using Oledb

有没有一种方法可以使用ADO.Net/Oledb将数据导出到excel(xslx),而无需使用任何第三方库?

这是工作代码...首先,您需要在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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM