将gridview的内容导出到Excel 2007+

时间:2013-06-21 15:09:51

标签: c# excel gridview

嗨,我在使用下面的代码将gridview导出到Excel时遇到了一些麻烦。它似乎工作正常,除了当我打开文件时它告诉我它不是指定的扩展名格式,但是如果忽略它它仍然打开。我对编码很新,并且不确定将其正确地设置为xl格式的最佳方法(以上内容发生在实时或MO服务器上)。

同样在我的本地VS2012当我在调试模式(本地主机)中运行并单击按钮时,我似乎得到了程序抛出和异常

sender {Text = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} object {System.Web.UI.WebControls.Button}

    #region Event to Export the table to MS Excel when the export button is clicked
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dt1 = (DataTable)ViewState["dtList"];
            if (dt1 == null)
            {
                throw new Exception("No Records to Export");
            }
            string Path = "c:\\OrderTrackerExportsFromTP\\CircuitsOrderTrackFor_" + DateTime.Now.ToString("yyyyMMdd Hmmss") + ".xls";
            FileInfo FI = new FileInfo(Path);
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
            DataGrid DataGrd = new DataGrid();
            DataGrd.DataSource = dt1;
            DataGrd.DataBind();

            DataGrd.RenderControl(htmlWrite);
            string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
            stringWriter.ToString().Normalize();
            vw.Write(stringWriter.ToString());
            vw.Flush();
            vw.Close();
            WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
    //Push the attachment to the user with the response object from the button click event
    public static void WriteAttachment(string FileName, string FileType, string content)
    {
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.ClearHeaders();
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
        Response.ContentType = FileType;
        Response.Write(content);
        Response.End();

    }
#endregion

0 个答案:

没有答案