有没有办法在不使用任何第三方库的情况下使用ADO.Net/Oledb将数据导出到excel(xslx)?
答案 0 :(得分:0)
如果您在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
答案 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();