C# Export DataTable, DataSet ไปเป็น excel

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderators: mindphp, ผู้ดูแลกระดาน

User avatar
jataz2
PHP Super Member
PHP Super Member
Posts: 238
Joined: 22/02/2011 11:48 am

C# Export DataTable, DataSet ไปเป็น excel

Post by jataz2 » 22/02/2011 3:03 pm

Code: Select all

using System.Text;

protected void imgExportToExcel_Click(object sender, ImageClickEventArgs e)
    {
        DataTable dtlocal = null;  // DataTable dtlocal = ds.Tables[0];

        if (Session["fdt"] != null)
            dtlocal = (DataTable)Session["fdt"];

        if (dtlocal != null)
        {
            if (dtlocal.Rows.Count > 0)
            {
                string attachment = "attachment; filename=[color=#FF0000]YourFileName.xls[/color]";
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                Response.ContentEncoding = Encoding.Default;
                Response.ContentType = "application/vnd.ms-excel";
                string tab = "";
                foreach (DataColumn dc in dtlocal.Columns)
                {
                    Response.Write(tab + dc.ColumnName);
                    tab = "\t";
                }
                Response.Write("\n");

                int i;
                foreach (DataRow dr in dtlocal.Rows)
                {
                    tab = "";
                    for (i = 0; i < dtlocal.Columns.Count; i++)
                    {
                        Response.Write(tab + dr[i].ToString());
                        tab = "\t";
                    }
                    Response.Write("\n");
                }

                Response.End();
            }
        }
    }

  • Similar Topics
    Replies
    Views
    Last post

Return to “Programming - C/C++ & java & Python”

Who is online

Users browsing this forum: No registered users and 16 guests