ashx Excel로 데이터 내보내기

7340 단어
하나, datatable에서 Excel을 내보내면 다음과 같은 방법으로 경로를 선택할 수 있습니다.
 /// 
    /// DataTable Excel
    /// 
    /// DataTable 
    ///  
    /// httpcontext
    public void CreateExcel(DataTable dt, string FileName, HttpContext httpContext)
    {
        httpContext.Response.Clear();
        httpContext.Response.Charset = "UTF-8";
        httpContext.Response.Buffer = true;
        httpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        httpContext.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
        httpContext.Response.ContentType = "application/ms-excel";
        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) + "
"; foreach (DataRow row in myRow) { for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += row[i].ToString() + "
"; } else { ls_item += row[i].ToString() + "\t"; } } httpContext.Response.Output.Write(ls_item); ls_item = string.Empty; } httpContext.Response.Output.Flush(); httpContext.Response.End(); }

前端页面调用方法如下:

                Excel 내보내기

둘째, 데이터테이블은 Excel을 내보내서 서버에 저장합니다.방법은 다음과 같습니다.
 /// 
    /// DataTable Excel
    /// 
    /// DataTable 
    ///  
    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) + "
"; 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) + "
"; sw.Write(line); } sw.Close(); fs.Close(); }

프런트엔드 호출 방법:
                     Excel 내보내기
     function Import() {
         $.post("Import.ashx", {}, function (data) {
             alert(" ");
         });
     }

  
 

좋은 웹페이지 즐겨찾기