【问题标题】:Export DataTable to Excel asp将数据表导出到 Excel asp
【发布时间】:2013-04-24 12:19:16
【问题描述】:

我有一个将数据导出到 Excel 文件的网页。我遇到的唯一问题是,当我尝试打开 excel 文件时,我收到一条消息,提示“您尝试打开的文件的格式与文件扩展名指定的格式不同。验证文件没有损坏并且来自在打开文件之前受信任的来源。”。我怎样才能摆脱这个消息。为了进行导出,我使用了我在另一篇文章中找到的函数。这是代码...

private void ExporttoExcel(DataTable table)
{
    //Response.Clear();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ContentType = "application/excel";
    HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=TestingReports");
    HttpContext.Current.Response.Charset = "UTF-8";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1252");
    // Sets font
    HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
    HttpContext.Current.Response.Write("<BR><BR><BR>");
    // Sets the table border, cell spacing, border color, font of the text, background, foreground, font height
    HttpContext.Current.Response.Write("<Table bgColor='#ffffff' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
    // Am getting my grid's column headers
    int columnscount = table.Columns.Count;

    // Write in new column
    for (int j = 0; j < columnscount; j++)
    {
        HttpContext.Current.Response.Write("<Td style='font-size:15.0pt; text-align:center; width:80.0pt; border-width:1.0pt; border-color:#000000; border-style:solid; height:22.0pt;'>");
        // Get column headers  and make it as bold in excel columns
        HttpContext.Current.Response.Write("<B>");
        HttpContext.Current.Response.Write(table.Columns[j].ToString());
        HttpContext.Current.Response.Write("</B>");
        HttpContext.Current.Response.Write("</Td>");
    }
    HttpContext.Current.Response.Write("</TR>");

    // Write in new row
    foreach (DataRow row in table.Rows)
    {
        HttpContext.Current.Response.Write("<TR>");
        for (int i = 0; i < table.Columns.Count; i++)
        {
            HttpContext.Current.Response.Write("<Td style='width:80.0pt; text-align:center; border-width:0.5pt; border-color:#000000; border-style:solid; height:22.0pt;'>");
            HttpContext.Current.Response.Write(row[i].ToString());
            HttpContext.Current.Response.Write("</Td>");
        }
        HttpContext.Current.Response.Write("</TR>");
    }
    HttpContext.Current.Response.Write("</Table>");
    HttpContext.Current.Response.Write("</font>");
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();

    //Response.Write("TestingReports.xls");
    //Response.Flush();
    //Response.End();
}

任何帮助将不胜感激。提前谢谢你。

【问题讨论】:

标签: c# asp.net excel


【解决方案1】:

以下方法用于从您的 c# 代码导出到 excel 中。

// fileName = your file name like test.xls
// dt = your data table
// caption = it is caption which display on top of excel file.


 public static void Export(string fileName, DataTable dt, string Caption)
        {


            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
            HttpContext.Current.Response.Charset = "windows-1254"; //ISO-8859-13 ISO-8859-9  windows-1254

            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            string header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title></title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1254\" />\n<style>\n</style>\n</head>\n<body>\n";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid

                    Table table = new Table();
                    table.GridLines = GridLines.Horizontal;
                    //table.CellSpacing = 17;                                      

                    if (Caption.Trim() != "")
                        table.Caption = "<span style='background-color: #FFFFFF; color: #666666; font-size: 14pt; font-weight: bold; padding: 5px 0px; height: 30px;'>" + Caption + "</span>";

                    TableRow row = null;
                    row = new TableRow();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        TableHeaderCell headerCell = new TableHeaderCell();
                        headerCell.Text = dt.Columns[i].ColumnName;
                        PrepareControlForExport(headerCell);
                        row.Cells.Add(headerCell);
                    }
                    table.Rows.Add(row);
                    foreach (DataRow rows in dt.Rows)
                    {
                        row = new TableRow();
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            TableCell RowCell = new TableCell();
                            RowCell.Text = rows[i].ToString();
                            PrepareControlForExport(RowCell);
                            row.Cells.Add(RowCell);
                        }
                        table.Rows.Add(row);
                    }

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

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.ContentType = "text/csv";
                    HttpContext.Current.Response.Write(header + sw.ToString());
                    HttpContext.Current.Response.End();

                 }
            }
        }

        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"));
                }
                else if (current is Label)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
                }

                if (current.HasControls())
                {
                    ReportExport.PrepareControlForExport(current);
                }
            }
        }

【讨论】:

    【解决方案2】:

    将您的内容类型更改为application/ms-excel 并在文件名中包含扩展名。即

    Response.ContentType = "application/ms-excel";
    Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls");
    

    我之前用 3 种不同的方式写了一封 article。您可以使用其中一种方法。

    HTML表格方式:

        public void ExportToExcel(DataTable table)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();
    
            //Begin Table
            context.Response.Write("<table><tr>");
    
            //Write Header
            foreach (DataColumn column in table.Columns)
            {
                context.Response.Write("<th>" + column.ColumnName + "</th>");
            }
            context.Response.Write("</tr>");
    
            //Write Data
            foreach (DataRow row in table.Rows)
            {
                context.Response.Write("<tr>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    context.Response.Write("<td>" + row[i].ToString().Replace(",", string.Empty) + "</td>");
                }
                context.Response.Write("</tr>");
            }
    
            //End Table
            context.Response.Write("</table>");
    
            context.Response.ContentType = "application/ms-excel";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls");
            context.Response.End();
        }
    

    【讨论】:

      【解决方案3】:

      使用“application/x-msexcel”或“application/vnd.ms-excel”MIME 类型在 Microsoft Excel 中打开网页内容的网站在尝试在 Excel 中打开文件时可能会遇到以下警告提示2007:

      “您尝试打开的文件 '[filename]' 的格式与文件扩展名指定的格式不同。在打开文件之前,请确认文件没有损坏并且来自受信任的来源。您是否现在要打开文件吗?” (是 | 否 | 帮助)

      如果用户单击“是”,文件将按预期打开。如果用户单击“否”,则文件可能仍会打开,或者可能会提示第二次,如果用户再次选择“否”则不会打开。

      更多关于http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx的信息

      【讨论】:

        【解决方案4】:

        虽然您所做的工作可能会奏效,但读取中型到大型文件也需要很长时间。检查this excel reader out. 既然你有数据集,你所要做的就是循环创建一个文件流,你就会有你的 excel 文档

        【讨论】:

          猜你喜欢
          • 2023-03-15
          • 1970-01-01
          • 2010-09-21
          • 2017-03-27
          • 1970-01-01
          • 2015-08-05
          • 2010-09-19
          • 1970-01-01
          相关资源
          最近更新 更多