1. 程式人生 > >C# asp.net 實現匯出Excel

C# asp.net 實現匯出Excel

轉自http://www.cnblogs.com/zhangjd/p/5673950.html

兩個方法

一、實現DataTable資料匯出到本地,需要自己傳進去匯出的路徑。

/// <summary>
/// DataTable匯出到Excel
/// </summary>
/// <param name="table">DataTable型別的資料來源</param>
/// <param name="file">需要匯出的檔案路徑</param>
public void dataTableToCsv(DataTable table, string file)
{
    string title = "";
    FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
    StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
    for (int i = 0; i < table.Columns.Count; i++)
    {
        title += table.Columns[i].ColumnName + "\t"; //欄位:自動跳到下一單元格
    }
    title = title.Substring(0, title.Length - 1) + "\n";
    sw.Write(title);
    foreach (DataRow row in table.Rows)
    {
        string line = "";
        for (int i = 0; i < table.Columns.Count; i++)
        {
            line += row[i].ToString().Trim() + "\t"; //內容:自動跳到下一單元格
        }
        line = line.Substring(0, line.Length - 1) + "\n";
        sw.Write(line);
    }
    sw.Close();
    fs.Close();
}

二、實現DataTable資料匯出到本地,路徑可以由使用者自主選擇。

/// <summary>
/// DataTable匯出到Excel
/// </summary>
/// <param name="dt">DataTable型別的資料來源</param>
/// <param name="FileType">檔案型別</param>
/// <param name="FileName">檔名</param>
public void CreateExcel(DataTable dt, string FileType, string FileName)
{
    Response.Clear();
    Response.Charset = "UTF-8";
    Response.Buffer = true;
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
    Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
    Response.ContentType = FileType;
    string colHeaders = string.Empty;
    string ls_item = string.Empty;
    DataRow[] myRow = dt.Select();
    int i = 0;
    int cl = dt.Columns.Count;
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        ls_item += dt.Columns[j].ColumnName + "\t"; //欄位:自動跳到下一單元格
    }
    ls_item = ls_item.Substring(0, ls_item.Length - 1) + "\n";
    foreach (DataRow row in myRow)
    {
        for (i = 0; i < cl; i++)
        {
            if (i == (cl - 1))
            {
                ls_item += row[i].ToString() + "\n";
            }
            else
            {
                ls_item += row[i].ToString() + "\t";
            }
        }
        Response.Output.Write(ls_item);
        ls_item = string.Empty;
    }
    Response.Output.Flush();
    Response.End();
}

三、方法的呼叫。

第一種方法的呼叫:

this.dataTableToCsv(dt, @"C:\Users\Admin\Desktop\收聽率" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls"); //呼叫函式
第二種方法的呼叫:
CreateExcel(dt, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");//呼叫函式

這兩種方法都是可以直接呼叫的,只需要傳入需要的引數即可。

如果是通過前臺js方式實現,跳轉href

為實現資料匯出的頁面地址,我是通過前臺跳轉到ashx頁面實現的

ashx頁面內容

public void ProcessRequest(HttpContext context)
        {string message = "";
            string Action = context.Request["Action"];
            switch (Action)
            {case "Excel":
                    DataTable Radio = GetExcleData(context); //獲取匯出資料來源
                    RadioCommon helper = new RadioCommon();
                    helper.ExportExcel(Radio, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
                    break;
            }
            context.Response.Write(message);
        }
js部分內容
$("#Excel").bind('click', function () {
                var url = "AjaxHandler/RadioFamilyDayNumber.ashx?Action=Excel";
                window.location.href = url;//匯出Excel
            })