C # ASP. NET implementation Export Excel

Source: Internet
Author: User

Transfer from http://www.cnblogs.com/zhangjd/p/5673950.html

This period of time used to export Excel function, this function is more commonly used, I often have two methods, now tidy up, easy to see later.

First, the implementation of DataTable data export to local, you need to pass in the exported path.

1234567891011121314151617181920212223242526272829 /// <summary>/// DataTable导出到Excel/// </summary>/// <param name="table">DataTable类型的数据源</param>/// <param name="file">需要导出的文件路径</param>public voiddataTableToCsv(DataTable table, stringfile){    stringtitle = "";    FileStream fs = newFileStream(file, FileMode.OpenOrCreate);    StreamWriter sw = newStreamWriter(newBufferedStream(fs), System.Text.Encoding.Default);    for(inti = 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 intable.Rows)    {        stringline = "";        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();}

Second, the realization of DataTable data export to local, the path can be selected by the user.

12345678910111213141516171819202122232425262728293031323334353637383940414243 /// <summary>/// DataTable导出到Excel/// </summary>/// <param name="dt">DataTable类型的数据源</param>/// <param name="FileType">文件类型</param>/// <param name="FileName">文件名</param>publicvoidCreateExcel(DataTable dt, stringFileType, stringFileName){    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;    stringcolHeaders = string.Empty;    stringls_item = string.Empty;    DataRow[] myRow = dt.Select();    inti = 0;    intcl = dt.Columns.Count;    for(intj = 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 inmyRow)    {        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();}

Third, the invocation of the method.

Invocation of the first method:

1 this.dataTableToCsv(dt, @"C:\Users\Admin\Desktop\收听率"+ DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls"); //调用函数

Invocation of the second method:

1 CreateExcel(dt, "application/ms-excel""Excel"+ DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");//调用函数

Both of these methods can be called directly, only need to pass in the required parameters.

If it is through the foreground JS way to achieve, jump href for the implementation of data export page address, I was through the foreground to jump to the ASHX page to achieve

Ashx page Content

public void ProcessRequest (HttpContext context)        {string message = "";            String Action = context. request["Action"];            Switch (Action)            {case ' Excel ':                    DataTable Radio = getexcledata (context);//Get Export Data source                    Radiocommon helper = new Radiocommon ();                    Helper. Exportexcel (Radio, "Application/ms-excel", "Excel" + DateTime.Now.ToString ("Yyyy-mm-dd hhmmss"));                    break;            }            Context. Response.Write (message);        }

JS section Content

  $ ("#Excel"). Bind (' click ', Function () {                var url = "Ajaxhandler/radiofamilydaynumber.ashx? Action=excel ";                window.location.href = url;//export Excel            })

C # ASP. NET implementation Export Excel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.