C#連接Excel和生成Excel

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.IO;
using System.Text; //連接Excel需要用的命名空間


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGv();
}
}

//綁定數據源
protected void BindGv()
{
gvStudents.DataSource = GetDs();
gvStudents.DataBind();
}

//獲得數據源
protected DataSet GetDs()
{
string excelPath = Server.MapPath("school.xls");
string conString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + "; Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(conString);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [students]", con);
DataSet ds = new DataSet();
da.Fill(ds);

return ds;
}

//生成Excel
protected void btnExcel_Click(object sender, EventArgs e)
{
Export("student.xls");
}

//生成Excel的方法
private void Export(string FileName)
{
// Response.Charset = "GB2312";
// Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application / ms - excel";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gvStudents.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}

#region **** 生成Excel必須要重寫的方法 ****
//如果沒有下面方法會報錯類型“GridView”的控件“gvStudents”必須放在具有 runat=server 的窗體標記內
public override void VerifyRenderingInServerForm(Control control)
{

}
#endregion

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章