Analytics

2010年10月14日 星期四

[C#]使用 OleDbDataAdapter從Excel讀取資料再匯出EXCEL檔案(Using OleDbDataAdapter to read data from Excel files and then export EXCEL)


問題
使用 OleDbDataAdapter從Excel讀取資料再匯出EXCEL檔案



解決方法
OleDbConnection con = new OleDbConnection(DBPath);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + rbUploadOption.SelectedItem.Value + "$] ", con);
DataSet ds = new DataSet();
da.Fill(ds, "TEST");

GridView gvExport = new GridView();
gvExport.DataSource = ds;
gvExport.DataBind();

string ExportFilename = DateTime.Now.ToString("yyyyMMddHHmmss");
Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=" + ExportFilename);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
Response.Charset = "uft8";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gvExport.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString().Replace("<div>", "").Replace("</div>", ""));
Response.End();

沒有留言:

熱門文章