[英]NPOI return a .xls file with NancyFx
我正在嘗試創建導出功能,在該功能中,我將創建的.xls文件發送給用戶。
我正在使用NancyFx進行請求,並使用NPOI進行excel文件的創建。 無法弄清楚此代碼出了什么問題,我得到了OK 200響應,但沒有內容/文件返回。
public class ExportService
{
private HSSFWorkbook HssfWorkbook { get; set; }
public ExportService()
{
HssfWorkbook = new HSSFWorkbook();
}
public Response Export()
{
string fileName = "test2.xls";
var response = new Response();
response.Headers.Add("Content-Disposition", string.Format("attachment;filename={0}", fileName));
InitializeWorkbook();
GenerateData();
response.Contents(WriteToStream());
return response.AsAttachment(fileName, "application/vnd.ms-exce");
}
private MemoryStream WriteToStream()
{
//Write the stream data of workbook to the root directory
MemoryStream file = new MemoryStream();
HssfWorkbook.Write(file);
return file;
}
private void GenerateData()
{
var sheet1 = HssfWorkbook.CreateSheet("Försäljning");
sheet1.CreateRow(0).CreateCell(0).SetCellValue("Detta är ett test");
int x = 1;
for (int i = 1; i <= 15; i++)
{
var row = sheet1.CreateRow(i);
for (int j = 0; j < 15; j++)
{
row.CreateCell(j).SetCellValue(x++);
}
}
}
private void InitializeWorkbook()
{
////create a entry of DocumentSummaryInformation
var documentSummaryInformation = PropertySetFactory.CreateDocumentSummaryInformation();
documentSummaryInformation.Company = "Test Company";
HssfWorkbook.DocumentSummaryInformation = documentSummaryInformation;
////create a entry of SummaryInformation
var summaryInformation = PropertySetFactory.CreateSummaryInformation();
summaryInformation.Subject = "Test Subject";
HssfWorkbook.SummaryInformation = summaryInformation;
}
}
問題是我的請求來自AJAX調用。 需要保存文件,然后將用戶重定向到在我的AJAX響應中創建的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.