asp.net导出数据到Excel的两种方法

public void CreateExcel(DataTable dt,string FileName)//HttpResponse Page.Response
    {
        string FileType = "application/ms-excel";
        Response.Clear();
        Response.Charset = "UTF-8";
        Response.Buffer = true;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + FileName + ".xls\"");
        Response.ContentType = FileType;
        string colHeaders = string.Empty;
        colHeaders = '标题'
        Response.Output.Write(colHeaders);
        colHeaders = string.Empty;
        string ls_item = string.Empty;
        DataRow[] myRow = dt.Select();
        int cl = dt.Columns.Count;
        foreach (DataRow row in myRow)
        {
            int count = 0;
            for (int i = 0; i < cl; i++)
            {
                if (i == (cl - 1))
                {
                    ls_item += row[i].ToString() + "\n";
                }
                else
                {
                    if(count < 2)
                    {
                        ls_item = ls_item + "" + row[i].ToString() + "\t";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }
                count++;
            }
            Response.Output.Write(ls_item);
            ls_item = string.Empty;
        }
        Response.Output.Flush();
        Response.End();
    }

第二种用HttpContext.Current.Response。这种能够解决导出Excel科学记数法的问题。

这个方法的原文链接https://www.cnblogs.com/JsonShare/p/4872173.html

public void CreateExcel_t(DataTable dt, string FileName) {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
        StringBuilder table = new StringBuilder();
        table.Append("");
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            table.Append("");
        }
        table.Append("");
        for (int i = 0 ; i < dt.Rows.Count; i++)
        {
            table.Append("");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                table.Append("");
            }
            table.Append("");
        }
        table.Append("
"); table.Append(dt.Columns[i].Caption.ToString());//表格的标题 table.Append("
"); table.Append(dt.Rows[i][j].ToString()); table.Append("
"); HttpContext.Current.Response.Write(table); HttpContext.Current.Response.End(); }


你可能感兴趣的:(exce,asp.net)