在get调用中通过httpresponse返回一个工作簿,该方法用于旧版本的ClosedXML,现在返回一个空工作簿-工作簿选项卡被创建并正确命名,但为空。
示例代码-基本响应
public HttpResponseMessage Get([FromUri]ControlReportsView model)
{
string client = "EU";
ClosedXML.Excel.XLWorkbook workbook = CreateWorkbook(model, client);
MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition.FileName = string.Format("{0}_{1:yyyyMMdd hhmmtt} to {2:yyyyMMdd hhmmtt}.xlsx", model.Type.ToString(), model.StartDate, model.EndDate);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
Private = true,
MaxAge = TimeSpan.FromSeconds(300)
};
return response;
}
private static ClosedXML.Excel.XLWorkbook CreateWorkbook(ControlReportsView model, string client)
{
using (var workbook = new ClosedXML.Excel.XLWorkbook())
{
CreateTestTab(model, client, workbook);
return workbook;
}
}
private static void CreateTestTab(ControlReportsView model, string client, XLWorkbook workbook)
{
var worksheet = workbook.Worksheets.Add("Sample Sheet");
var firstRow = worksheet.FirstRow();
firstRow.Cell("A").Value = "Hello World!";
}
public class ControlReportsView
{
public enum ControlReportType
{
[Description("R")]
Inbound,
[Description("S")]
Outbound
}
public ControlReportType Type { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
我怀疑现在有一个更优雅的工具来做响应,我不知道。
我有另一个文件,我通过另一个方法成功返回,但我不愿意对当前文件的设置做这么大的改变:
var stream = new MemoryStream();
workbook.SaveAs(stream);
byte[] fileArray = stream.ToArray();
//build file name
DashObject FarmInfo = (DashObject)MySession.Info;
string ProjName = FarmInfo.ProjectName;
string datemade = DateTime.Now.ToString("yyyyMMdd-HHmmss");
string docName = String.Format("Subscribers_{0}_{1}.xlsx", ProjName, datemade);
Response.ContentType = "application/octet-stream";
string attachVal = "attachment; filename=" + docName;
Response.AppendHeader("Content-Disposition", attachVal);
Response.BinaryWrite(fileArray);
Response.End();
哇,真奇怪。
数据从来没有进入工作表,即使他们被创建。
删除Using子句以某种方式排序:
private static ClosedXML.Excel.XLWorkbook CreateWorkbook(ControlReportsView model, string client)
{
ClosedXML.Excel.XLWorkbook workbook = new ClosedXML.Excel.XLWorkbook();
CreateTestTab(model, client, workbook);
return workbook;
}
我怀疑由于某种原因,使用中的工作表没有正确地来回传递-有人能确认吗?