using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using SysCore;

public partial class System_GrfPrinter_ExportToExcel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ToExcel();
    }
    public void ToExcel()
    {
        Response.Clear();     
        Response.Buffer = true;     
        Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.
        Now.ToString("yyyyMMddHHmm")+".xls");           
        Response.ContentEncoding = System.Text.Encoding.UTF8;   
        Response.ContentType = "application/ms-excel";
        this.EnableViewState = false;

        string sql_detail = Session[Request.QueryString["sql_print_detail_session_id"]].ToString();
        string export_field = Session[Request.QueryString["sql_print_detail_session_id"] + "_export_field"].ToString();
        string sql = "select " + export_field + " from (" + sql_detail + ") tb ";
        Session["print_sql_main"] = "";
        Session["print_sql_detail"] = sql;
        SqlUtil su = new SqlUtil();
        DataTable dt = su.GetDataTable(sql, null);
        int col_count = dt.Columns.Count;
        string table = "<table border='1'>\n<tr>";
        for (int i = 0; i < col_count; i++)
        {
            string col_name = dt.Columns[i].ColumnName;
            table += "<th>" + col_name + "</th>";
        }
        table += "</tr>\n";
        foreach (DataRow dr in dt.Rows)
        {
            table += "<tr>";
            for (int i = 0; i < col_count; i++)
            {
                table += "<td>" + dr[i].ToString() + "</td>";
            }
            table += "</tr>\n";
        }
        table += "</table>";


        string doc = @"<html>
    <head>
        <meta http-equiv='Content-Type' content='text/html' charset='utf-8'>
        <style>
        /*td{mso-number-format:'\@';}*/
        </style>
    </head>
    <body>";

        Response.Write(doc+table);
        Response.Write("<body></html>");
    } 
 
}