The NET page exports the Excel instance code

  • 2020-09-16 07:26:42
  • OfStack


public static void CreateExcel(DataSet ds)
        {
            string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
            string colHeaders = "", ls_item = "";
            // Define table objects and row objects to use simultaneously DataSet Initialize its value 
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();// Can be similar to dt.Select("id>10") To achieve the purpose of data screening 
            int i = 0;
            int cl = dt.Columns.Count;

            // Gets the column headings of the data table between the headings \t Split, and finally 1 Column headings followed by a carriage return 
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))// The last 1 The column, \n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            HttpContext.Current.Response.Write(colHeaders);
            // to HTTP Write the obtained data information in the output stream 
            // Process the data line by line   
            foreach (DataRow row in myRow)
            {
                // Current row data write HTTP Output stream, and empty ls_item For downstream data     
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))// The last 1 The column, \n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }
                HttpContext.Current.Response.Write(ls_item);
                ls_item = "";
            }
            HttpContext.Current.Response.End();
        }


Related articles: