我正在尝试创建一个导出功能,我将创建的.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;
}
}
答案 0 :(得分:1)
问题是我的请求来自AJAX调用。 需要保存文件,然后将用户重定向到我的AJAX响应中创建的文件。