完整教程链接:ASP.Net: EshineASPNet-基于ASP.Net敏捷开发开源框架
Excel的导入与导出是后台最常用的功能之一了,这里分享一下实现方式。
要实现excel导入,这里使用OLEDB,先引用System.Data.OleDb。
public DataTable InputExcel(string TableName)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "select * from [" + TableName + "$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
DataTable dt = new DataTable();
myCommand.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
上面的函数以Sheet名作为输入,支持中文,可以选择Excel里面的哪张表来导入,读取的数据保存在DataTable。然后就可以对DataTable里面的数据逐行处理并插入数据库。
如果数据是存在GridView控件里面的,那么有个简便方法可以导出,先添加System.Web.UI和System.Web.UI.HtmlControls引用。
public void gridviewtoexcel(GridView gv, string filename)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
for (int i = 0; i < gv.Rows.Count; i++)
{
if (gv.Rows[i].FindControl("GridView2") != null)
{
gv.Rows[i].Cells.RemoveAt(0);
gv.Rows[i].Cells.RemoveAt(gv.Rows[i].Cells.Count - 1);
}
}
gv.EnableViewState = false;
// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;
// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(gv);
page.RenderControl(htw);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
System.Web.HttpContext.Current.Response.Charset = "UTF-8";
System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.Default;
System.Web.HttpContext.Current.Response.ContentType = "application/excel";
string style = @"