导航

數據導出(一):Dataset(或DataTable)導出到excel

Posted on 2009-11-02 14:57  杨彬Allen  阅读(273)  评论(0)    收藏  举报

這段代碼也是網上用的最多的一段function,優點就是代碼清晰,缺點就是導出的excel樣式簡單。

因為用的是繁體版本,所以開始這裡不管是用“UTF-8”還是“UTF-7”還是“GB2313”還是所謂的web.config中保持一致。我都試過,都不能解決亂碼問題,只有這裡寫成Default才不會出現亂碼,特記下來。

/// <summary>
    
/// DataTable導出到Excel.繁體OS,無亂碼問題.
    
/// </summary>
    
/// <param name="dt"></param>
    
/// <param name="strFileName">含.xls後綴</param>
    public void DownloadAsExcel(DataTable dt, string strFileName)
    {
        
try
        {
            StringWriter sw 
= new StringWriter();
            
string colstr = "";
            
foreach (DataColumn col in dt.Columns)
            {
                colstr 
+= col.ColumnName + "\t";
            }
            sw.WriteLine(colstr);

            
foreach (DataRow row in dt.Rows)
            {
                colstr 
= "";
                
foreach (DataColumn col in dt.Columns)
                {
                    colstr 
+= row[col.ColumnName].ToString() + "\t";
                }
                sw.WriteLine(colstr);
            }
            sw.Close();
            System.Web.HttpContext.Current.Response.AddHeader(
"Content-Disposition""attachment; filename=" + strFileName + "");
            System.Web.HttpContext.Current.Response.ContentType 
= "application/ms-excel";
            System.Web.HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.Default;
            System.Web.HttpContext.Current.Response.Write(sw);
            System.Web.HttpContext.Current.Response.End();
        }
        
catch (Exception ex)
        {
            lblMessage.Text 
= ex.Message;
        }
    }