将数据表导出到Excel [英] Export Data Table to Excel
本文介绍了将数据表导出到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我正在使用以下代码在excel中导出数据表记录.它对我不起作用.我收到异常由于代码已优化或本机框架位于调用堆栈的顶部,无法评估表达式".
我如何解决我的问题.请帮助我
Hi All,
I am using following code for exporting data table record in excel.It does not work for me.I am getting exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack".
How I resolve my problem. Please Help me
protected void ExportDatatableToXLS(DataTable dtExports)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Member.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Table mainTable = new Table();
TableRow trExport;
TableCell cellExport;
if (dtExports.Rows.Count > 0)
{
trExport = new TableRow();
for (int col = 0; col < dtExports.Columns.Count; col++)
{
cellExport = new TableCell();
cellExport.Text = dtExports.Columns[col].ToString();
cellExport.BorderWidth = 1;
cellExport.Style.Add("font-weight", "bold");
cellExport.Style.Add("text-align", "Left");
cellExport.BackColor = System.Drawing.Color.Silver;
trExport.Cells.Add(cellExport);
mainTable.Rows.Add(trExport);
}
for (Int32 ai = 0; ai < dtExports.Rows.Count; ai++)
{
trExport = new TableRow();
for (Int16 cl = 0; cl < dtExports.Columns.Count; cl++)
{
cellExport = new TableCell();
cellExport.Text = Convert.ToString(dtExports.Rows[ai][cl]).Trim();
cellExport.BorderWidth = 1;
cellExport.Style.Add("text-align", "left");
cellExport.Style.Add("vertical-align", "top");
trExport.Cells.Add(cellExport);
}
mainTable.Rows.Add(trExport);
}
}
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
mainTable.RenderControl(hw);
Response.Flush();
Response.Write(hw.InnerWriter.ToString());
Response.Flush();
Response.End();
}
推荐答案
您只需将此代码放在最终catch语句之前
You just put this code before of the final catch statement
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
当您在asp.net中的文件下载"窗口中时,导致此异常的另一个愚蠢原因.原因是当下载的文件名包含任何空格时,您可能会收到此错误.您可以随时注意.
Another silly cause for this exception, when you are working file download window in asp.net. The reason is when the downloaded file name contains any spaces then u may get this error. You can keep an eye on that.
这篇关于将数据表导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文