0

嗨,我在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
4

0 回答 0