//導出Excel/Word方法
private bool ExportDataGrid(string FileType, string FileName) //導出Excel
{
try
{
//清除Response緩存內容
HttpContext.Current.Response.Clear();
//緩存輸出,並在完成整個響應之後將其發送
HttpContext.Current.Response.Buffer = true;
//strFileName指定輸出文件的名稱,注意其擴展名和指定文件類型相符,可以爲:.doc .xls .txt .htm
//strFileName = strFileName + ".xls";
//設置輸出流的HTPP字符集,確定字符的編碼格式
//HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//下面這行很重要, attachment 參數表示作爲附件下載,您可以改成 online在線打開
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName));
//Response.ContentType指定文件類型.可以爲application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他瀏覽器可直接支持文檔
HttpContext.Current.Response.ContentType = "application/ms-" + FileType;
//用GridView輸出
outTable.Columns["i_gzrz_id"].ColumnName = "流水號";
outTable.Columns["dtm_zxsj"].ColumnName = "撰寫時間";
outTable.Columns["action"].ColumnName = "日誌內容";
outTable.Columns["timeconsuming"].ColumnName = "耗時";
outTable.Columns["progress"].ColumnName = "進度";
outTable.Columns["important"].ColumnName = "重要程度";
GridView dv = new GridView();
dv.DataSource = outTable;
dv.DataBind();
try
{
dv.Page.EnableViewState = false;
}
catch
{ }
System.IO.StringWriter swBody = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hwBody = new System.Web.UI.HtmlTextWriter(swBody);
//dv表示輸出GridView,你也可以綁定datagrid,或其他支持obj.RenderControl()屬性的控件
dv.RenderControl(hwBody);
//消除亂碼特別設定,非常規方法
string strExcel = "";
strExcel = "";
strExcel += hwBody.InnerWriter.ToString();
HttpContext.Current.Response.Write(strExcel);
HttpContext.Current.Response.End();
return true;
}
catch
{
return false;
}
}