使用Oledb导出到excel(xlsx)

时间:2018-02-08 00:20:21

标签: c# asp.net .net asp.net-mvc-4

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

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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