1

I am reading data from a SQL Server 2008 database usnig NHibernate and I am getting a list of objects. I want to create an .xls Excel file on the fly and give it to user.

My problem is, I cannot make any temp files or folders in the server and cannot use any blob.

Any solutions?

4

2 回答 2

0

Does it have to be an .xls or is an .xlsx acceptable as well?

I'm the author of a simple .xlsx writer library for C# which supports writing to a stream without going through a file.

The documentation contains an example ASP.net MVC ActionResult - you can inherit from it and then override the GenerateWorkbook method to generate the Workbook from your Database Tables.

public abstract class ExcelResultBase : ActionResult
{
private readonly string _filename;

protected ExcelResultBase(string filename)
{
    _filename = filename;
}

protected abstract Workbook GenerateWorkbook();

public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }

    var workbook = GenerateWorkbook();
    if (workbook == null)
    {
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
        return;
    }

    context.HttpContext.Response.ContentType = "application/octet-stream";
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
    context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=\"" + _filename + "\"");
    workbook.Save(context.HttpContext.Response.OutputStream, CompressionLevel.NoCompression);
}
}
于 2013-08-20T06:19:21.157 回答
0

You can try with the ClosedXML library (to easily manipulate your workbook) saving it to a memory stream. Then, long story short, send the stream via http as usual.

public byte[] GetExcelByteStream(string filename)
{
    using (var workbook = new XLWorkbook(filename))
    {
            var worksheet = workbook.Worksheets.Add("Sample Sheet");
            worksheet.Cell("A1").Value = "Hello World!";
            using (var ms = new MemoryStream())
            {
                workbook.SaveAs(ms);
                return ms.ToArray();
            }
    }
}

For the web response the classic way:

var excelStream = GetExcelByteStream("MyExcelFilename");
context.Response.Clear(); 
context.Response.AddHeader("Content-Disposition",  "attachment;filename="+context.Request.Form["txtFileName"].ToString()); 
context.Response.AddHeader("Content-Length", excelStream.Length.ToString()); 
context.Response.ContentType = "application/octet-stream"; 
context.Response.BinaryWrite(excelStream); 

Hope it helps.

于 2013-08-20T06:32:01.860 回答