Excel作家飞

时间:2013-08-20 05:54:11

标签: c# sql-server asp.net-mvc-3 sql-server-2008

我正在从SQL Server 2008数据库中读取数据usnig NHibernate,我得到一个对象列表。我想动态创建一个.xls Excel文件并将其提供给用户。

我的问题是,我无法在服务器中制作任何临时文件或文件夹,也无法使用任何blob。

任何解决方案?

2 个答案:

答案 0 :(得分:0)

是否必须是.xls.xlsx也可以接受?

我是C#的a simple .xlsx writer库的作者,它支持在不经过文件的情况下写入流。

The documentation包含一个示例ASP.net MVC ActionResult - 您可以继承它,然后覆盖GenerateWorkbook方法以从数据库表生成工作簿。

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);
}
}

答案 1 :(得分:0)

您可以尝试使用ClosedXML库(轻松操作工作簿)将其保存到内存流中。然后,长话短说,像往常一样通过http发送流。

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();
            }
    }
}

对于网络响应的经典方式:

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); 

希望它有所帮助。