简体   繁体   English

在C#中导出到excel并显示错误,而不下载excel

[英]Export to excel in c# showing error and not downloading the excel

My code, where the collection of values retrived from DB and that values stored one by one in datatable.And loading that dataTable to worksheet of Excel 我的代码,从数据库中检索值的集合,并将这些值一一存储在数据表中,然后将该数据表加载到Excel工作表中

var dataTable = new DataTable();
var sb = new StringBuilder();
var resultvalues=methodtogetvalues() ;


if (resultvalues!= null && resultvalues.Count > 0)
{
    var icount = 1;

    foreach (var values in resultvalues)
    {
        if (icount == 1)
        {
            sb.Append(values.Id);
            icount += 1;
        }

        dataTable.Columns.Add("ID");
        dataTable.Rows.Add(values.Id);
    }
}

var firstName = context.Request.Params["FirstName"];
var lastName = context.Request.Params["LastName"];
var fileName = firstName+lastName+"_ProgramStatusHistory_"+DateTime.Now;

var tempText = Convert.ToString(sb);
var workBook = new ExpertXls.ExcelLib.ExcelWorkbook(ExpertXls.ExcelLib.ExcelWorkbookFormat.Xlsx_2007);
var accessedRangeStyle = workBook.Styles.AddStyle("ΑccessedRangeStyle");
accessedRangeStyle.Font.Size = 10;
accessedRangeStyle.Font.Bold = true;
accessedRangeStyle.Alignment.VerticalAlignment = ExpertXls.ExcelLib.ExcelCellVerticalAlignmentType.Center;
accessedRangeStyle.Alignment.HorizontalAlignment = ExpertXls.ExcelLib.ExcelCellHorizontalAlignmentType.Left;
workBook.Worksheets.AddWorksheet();

var workSheet = workBook.Worksheets[0];
workSheet.LoadDataTable(dataTable, 1, 1, true);
workSheet.AutofitColumns();
workBook.Worksheets.RemoveWorksheet("Sheet2");
workBook.Worksheets.RemoveWorksheet("Sheet3");
workBook.Worksheets.RemoveWorksheet("Sheet4");
workBook.LicenseKey = "gqmworCworOysrWitKyyorGzrLOwrLu7u7s=";

context.Response.Clear();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);

using (var MyMemoryStream = new System.IO.MemoryStream())
{
    workBook.Save(MyMemoryStream);
    MyMemoryStream.WriteTo(context.Response.OutputStream);
    context.Response.Flush();
    context.Response.End();
}

This code simply shows an alert box with the error message "Error". 此代码仅显示带有错误消息“ Error”的警报框。

I don't understand whats wrong. 我不明白怎么了 Can anyone redirect me with correct way. 谁能以正确的方式重定向我。

I would move this line of code outside the using statement: 我会将这段代码移到using语句之外:

context.Response.End();

also show your catch block. 还显示您的捕获块。 It's unlikely to be giving just a message of 'Error' I would suggest placing a breakpoint in the catch block and looking inside the error object. 不太可能只给出“错误”消息,我建议在catch块中放置一个断点并查看错误对象的内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM