Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中导出到Excel#_C#_Asp.net - Fatal编程技术网

C# 在c中导出到Excel#

C# 在c中导出到Excel#,c#,asp.net,C#,Asp.net,我有一个gridview页面。我需要下载excel格式的gridview数据。我使用以下代码下载到excel格式 public static void Export(string fileName, GridView gv) { string style = @"<style> .text { mso-number-format:\@;text-align:right; } </style> "; HttpContext.Current.Response.

我有一个gridview页面。我需要下载excel格式的gridview数据。我使用以下代码下载到excel格式

public static void Export(string fileName, GridView gv)
{
    string style = @"<style> .text { mso-number-format:\@;text-align:right; } </style> ";
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            HttpContext.Current.Response.Write(style);

            //  Create a table to contain the grid      
            System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();

            //  include the gridline settings  
            table.GridLines = gv.GridLines;

            //  add the header row to the table 
            if (gv.HeaderRow != null)
            {
                PrepareControlForExport(gv.HeaderRow);
                table.Rows.Add(gv.HeaderRow);
            }

            //  add each of the data rows to the table   
            foreach (GridViewRow row in gv.Rows)
            {
                // add numeric style for each cell   
                foreach (TableCell cell in row.Cells)
                {
                    cell.Attributes.Add("class", "text");
                }
                PrepareControlForExport(row);
                table.Rows.Add(row);
            }

            //  add the footer row to the table  
            if (gv.FooterRow != null)
            {
                PrepareControlForExport(gv.FooterRow);
                table.Rows.Add(gv.FooterRow);
            }

            //  render the table into the htmlwriter  
            table.RenderControl(htw);

            //  render the htmlwriter into the response
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }
}

/// <summary>
/// Replace any of the contained controls with literals        
/// </summary>       
/// <param name="control"></param> 
private static void PrepareControlForExport(Control control)
{
    for (int i = 0; i < control.Controls.Count; i++)
    {
        Control current = control.Controls[i];

        if (current is LinkButton)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
        }
        else if (current is ImageButton)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
        }
        else if (current is HyperLink)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
        }
        else if (current is DropDownList)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
        }
        else if (current is CheckBox)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
        }
        if (current.HasControls())
        {
            PrepareControlForExport(current);
        }
    }
}
publicstaticvoid导出(字符串文件名,GridView-gv)
{
字符串样式=@“。文本{mso编号格式:\@;文本对齐:右;}”;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(“内容处置”,string.Format(“附件;文件名={0}”,文件名));
HttpContext.Current.Response.ContentType=“应用程序/ms excel”;
使用(StringWriter sw=new StringWriter())
{
使用(HtmlTextWriter htw=新的HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(样式);
//创建一个包含网格的表
System.Web.UI.WebControls.Table Table=新的System.Web.UI.WebControls.Table();
//包括网格线设置
table.GridLines=gv.GridLines;
//将标题行添加到表中
如果(gv.HeaderRow!=null)
{
准备控制出口(gv.HeaderRow);
表.行.添加(gv.HeaderRow);
}
//将每个数据行添加到表中
foreach(gv.Rows中的GridViewRow行)
{
//为每个单元格添加数字样式
foreach(行中的表格单元格。单元格)
{
添加(“类”、“文本”);
}
准备控制输出(世界其他地区);
table.Rows.Add(行);
}
//将页脚行添加到表中
如果(gv.FooterRow!=null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
//将表呈现到htmlwriter中
表2.RenderControl(htw);
//将htmlwriter呈现到响应中
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
/// 
///用文本替换任何包含的控件
///        
///  
专用静态void PrepareControlForExport(控制)
{
对于(int i=0;i
下载该文件后,也会下载母版页的css文件。
请告诉我如何解决这个问题。

从C#创建真正Excel文件的最简单方法是使用ClosedXML库:。ClosedXML还可以作为NuGet软件包提供,以便于入门。

试试我的工作方法:

void ExportToExcel(GridView grdData, string filename)
{
    grdData.BorderStyle = BorderStyle.Solid;
    grdData.BorderWidth = 1;
    grdData.BackColor = Color.WhiteSmoke;
    grdData.GridLines = GridLines.Both;
    grdData.Font.Name = "Verdana";
    grdData.Font.Size = FontUnit.XXSmall;
    grdData.HeaderStyle.BackColor = Color.DimGray;
    grdData.HeaderStyle.ForeColor = Color.White;
    grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
    grdData.RowStyle.VerticalAlign = VerticalAlign.Top;

    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.Charset = "";
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");

    using (var sw = new StringWriter())
    {
        using (var htw = new HtmlTextWriter(sw))
        {
            grdData.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }
    }
} 

我不明白你的问题是什么,你能试着更详细地解释一下吗?导出数据是否比希望Excel打开HTML更容易?请解释你的答案(为什么这样做,与其他解决方案有什么不同)
        Response.ClearContent();

        Response.Buffer = true;

        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "excelname.xls"));

        Response.ContentType = "application/ms-excel";

        //which row you dont want in gridview
        GridView5.Columns[0].Visible = false;

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridView5.AllowPaging = false;

        GridView5.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();