在ASP.NET中将DataTable导出到Excel

时间:2014-03-13 08:11:08

标签: c# asp.net excel

调用此方法时,将带有html设计的整个页面移植到excel以及数据。 我只想要导出数据,不应该带有html设计。我找不到解决办法,请有人帮忙解决这个问题。

 public void ExportToExcel(DataTable dtExportData)
        {
            string strReportName = string.Empty;
            //StringWriter oStringWriter = null;
            //Html32TextWriter oHtmlTextWriter = null;
            //TableOneDayPassReport.Visible = true;
            ExcelGrid.EnableViewState = false;
            ExcelGrid.DataSource = dtExportData;
            ExcelGrid.DataBind();
            Response.Clear();
            Response.ClearHeaders();
            Response.Cache.SetCacheability(HttpCacheability.Private);
            Response.AddHeader("content-disposition", "attachment;filename=OwnTransportDetails.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            //TableOneDayPassReport.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            //Response.End();


            // strReportName = dtExportData.TableName;
            // Report_Month.InnerHtml = "<b>" + strReportName + " Report</b><br />";
            // ReportHead.Attributes.Add("style", "DISPLAY: block; VISIBILITY: visible");
            // TableOneDayPassReport.Visible = true;
            // //oStringWriter = new StringWriter();
            // //oHtmlTextWriter = new Html32TextWriter(oStringWriter);
            // ExcelGrid.EnableViewState = false;
            // ExcelGrid.DataSource = dtExportData;
            // ExcelGrid.DataBind();
            // Response.Clear();
            // Response.Buffer = true;
            // Response.AppendHeader("Content-Disposition", "attachment; filename=" + strReportName + ".xls");
            // Response.ContentType = "application/vnd.ms-excel";
            // TableOneDayPassReport.RenderControl(oHtmlTextWriter);
            // Response.Write(oStringWriter.ToString());
            // HttpContext.Current.ApplicationInstance.CompleteRequest();
            //// Response.End();
        }

3 个答案:

答案 0 :(得分:0)

您告诉浏览器将数据作为Microsoft Excel处理,但返回HTML数据。 Microsoft Excel非常聪明,可以显示HTML数据并显示数据。

如果您只想导出数据,则应使用EPPlus或Microsoft自己的SDK等库,并在服务器上创建Excel工作表。然后,退回此表。

答案 1 :(得分:0)

通过此代码检查此代码,您可以下载excel格式的.csv文件

这里你需要创建文件夹下载,你需要从该文件夹中提供服务器路径。 href="../../download/Orders.csv"

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
public partial class Admin_export_order : System.Web.UI.Page
{
    DBAccess dbAcc = new DBAccess();
    DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["admin_id"] == null)
            Response.Redirect("~/jbs/admin/login");
        if (!IsPostBack)
        {

            view_edit_supplier_BAL objHelp = new view_edit_supplier_BAL();
            DataTable dtHelp = objHelp.SearchSupplier("where page = 'export_order'", 18);
            if (dtHelp != null && dtHelp.Rows.Count > 0)
                lblhelp_msg.Text = dtHelp.Rows[0][0].ToString().Replace("''", "'");
        }
        StreamWriter sw;
        DataSet ds = new DataSet();
        export_bal objGet = new export_bal();
        ds = objGet.getDetails(5);

        try
        {


            for (int i = 0; i < ds.Tables.Count; i++)
            {
                sw = new StreamWriter(HttpContext.Current.Server.MapPath("~/download/Orders.csv"), false, Encoding.Unicode);

                int iColCount = ds.Tables[i].Columns.Count;
                for (int h = 0; h < iColCount; h++)
                {
                    sw.Write(ds.Tables[i].Columns[h]);
                    if (h < iColCount - 1)
                    {
                        sw.Write("\t");
                    }
                }
                sw.Write(sw.NewLine);

                foreach (DataRow dr in ds.Tables[i].Rows)
                {
                    for (int h = 0; h < iColCount; h++)
                    {
                        if (!Convert.IsDBNull(dr[h]))
                        {
                            if (dr[h].ToString().Contains("\r\n"))
                            {
                                string newdata = dr[h].ToString();
                                string newcolumn = newdata.Replace("\r\n", "");
                                sw.Write(newcolumn);
                            }
                            else
                            {

                                sw.Write(dr[h].ToString());

                            }
                        }
                        if (h < iColCount - 1)
                        {
                            sw.Write("\t");
                        }
                    }
                    sw.Write(sw.NewLine);

                }
                sw.Close();
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {

        }
    }


}





<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<table style="height: auto; width: 99.3%;" cellspacing="0" cellpadding="0" border="0"
        align="left" bgcolor="white">
        <tr>
            <td valign="top" bgcolor="#ffffff" align="left" width="8">
                <img height="8" width="8" alt="left bottom" src="../admin/images/top-left-corner.gif" />
            </td>
            <td bgcolor="#ffffff" width="99%">
            </td>
            <td bgcolor="#ffffff" align="right" width="8">
                <img height="8" width="8" align="right" alt="bottom right" src="../admin/images/right-top-corner.gif" />
            </td>
        </tr>
        <tr>
            <td colspan="3" valign="top">
                <table bgcolor="#ffffff" width="100%">
                    <tr>
                        <td width="36px" style="padding-left: 18px;">
                            <img src="images/category-img.gif" width="36" height="36" />
                        </td>
                        <td class="font_text_bold">
                            Export Orders
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td colspan="3" valign="top">
                <table bgcolor="#ffffff" width="100%" style="height: 660px;">
                    <tr>
                        <td valign="top">
                            <table width="100%">
                                <tr>
                                    <td colspan="3" valign="top">
                                        <table bgcolor="#ffffff" width="100%" style="padding-left: 7px;">
                                            <tr>
                                                <td>
                                                    <table width="99%" cellspacing="0" cellpadding="0" border="0" align="left" style="height: auto;">
                                                        <tr class="box_hd_bg_for_every">
                                                            <td align="left" valign="top" width="7">
                                                                <img src="images/left-add-pro.gif" alt="left" height="29" />
                                                            </td>
                                                            <td class="font_text_bold" width="100%" align="center" style="padding-right: 200px;
                                                                width: 1500px">
                                                                Export Setup
                                                            </td>
                                                            <td align="right">
                                                                <img src="images/right-add-pro.gif" alt="right" height="29" />
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td class="Gray_blowtr" colspan="3">
                                                                <table width="100%" height="100%" border="0" cellpadding="1" cellspacing="0">
                                                                    <tr>
                                                                        <td colspan="2" height="10">
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td colspan="2" align="left" class="font_text" style="padding-left: 5px;">
                                                                            Export file will be readable in Microsoft Excel or equivalent applications for ease
                                                                            review of data. Please click on below download button to Export file for Orders.
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td style="height: 20px;">
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td colspan="2" align="center" style="height: 30px;">
                                                                            <a href="../../download/Orders.csv" class="setpostion">&nbsp;<img style="border: 0"
                                                                                src="images/download.gif" alt="Download" title="Export" />
                                                                                &nbsp;</a>
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td style="height: 20px;">
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="3" valign="top">
                                        <table bgcolor="#ffffff" width="100%" style="padding-left: 7px;">
                                            <tr>
                                                <td>
                                                    <table width="99%" cellspacing="0" cellpadding="0" border="0" align="left" style="height: auto;">
                                                        <tr class="box_hd_bg_for_every">
                                                            <td align="left" valign="top" width="7">
                                                                <img src="images/left-add-pro.gif" alt="left" height="29" />
                                                            </td>
                                                            <td class="font_text_bold" width="100%" style="padding-right: 200px">
                                                                How to use this page
                                                            </td>
                                                            <td align="right">
                                                                <img src="images/right-add-pro.gif" alt="right" height="29" />
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td class="Gray_blowtr" colspan="3" style="padding-left: 10px; padding-right: 10px;
                                                                padding-top: 7px; padding-bottom: 7px;">
                                                                <asp:Label ID="lblhelp_msg" runat="server" Text=""></asp:Label>
                                                            </td>
                                                        </tr>
                                                        <tr style="height: 20px;">
                                                            <td>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td valign="bottom" bgcolor="#ffffff" align="left" width="8">
                <img height="8" width="8" alt="left bottom" src="images/bottom-left-corner.gif" />
            </td>
            <td bgcolor="#ffffff" width="99%">
            </td>
            <td bgcolor="#ffffff" align="right" width="8">
                <img height="8" width="8" align="right" alt="bottom right" src="images/bottom-right-corner.gif" />
            </td>
        </tr>
    </table>
</html>

答案 2 :(得分:0)

我找到了解决方案,请移动Response.End(); line to onclick事件并调用ExportToExcel(DataTable dtExportData)方法。

和Response.End();不应该在try ... catch语句里面,它应该在try ... catch语句之外