总结个比较简单 易懂的 导入导出 Excel,Word
一 导入Excel:把excel 作为数据源。
//自定义个 数据源方法 private DataSet CreateDataSource() { string strCon; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../新建 Microsoft Excel 工作表.xls") + "; Extended Properties=Excel 8.0;";//指定数据源的虚拟路径 OleDbConnection olecon = new OleDbConnection(strCon); OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [zzz$]", strCon);//是excel里面的表名字 DataSet myds = new DataSet(); myda.Fill(myds); return myds; } protected void Button1_Click(object sender, EventArgs e) { //绑定数据源 GridView1.DataSource = CreateDataSource(); GridView1.DataBind(); }
二 导出Excel,Word 直接定义 个导出函数,在对应的buntton的单击时间 调用
// 导出Excel protected void Button1_Click(object sender, EventArgs e) { export("application/ms-excel", "客户信息报表.xls"); } // 导出Word protected void Button2_Click(object sender, EventArgs e) { export("application/ms-word", "客户信息.doc"); } // 导出函数 private void export(string fileType, string fileName) { Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF7; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString()); Response.ContentType = fileType; this.EnableViewState = false; StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); GridView1.RenderControl(hw); Response.Write(tw.ToString()); Response.End(); } //导出方法,必须有!!!!!!!! public override void VerifyRenderingInServerForm(Control control){}