我正在尝试使用封闭的xml导出数据表,但这给了我空白。 这是我的代码
[HttpPost]
public FileResult ExportExcel()
{
List<ProductModel> productDetails = (List<ProductModel>)Session["CartItems"];
System.Data.DataTable dtExcel = CategoryDAL.ToDataTable(productDetails);
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dtExcel);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
}
}
当我调试时,我可以看到数据表中有数据,但它导出了一个空白的数据
答案 0 :(得分:1)
嘿,我已经为自己的建议写了一个excelexporter。 我使用本教程来开始excel导出:
这是我如何在控制器中运行Excel导出的代码段:
public async Task<FileResult> DownloadExcel(long id, CancellationToken token)
{
var entites= await _someRepository.GetSomethingAsync(id, token).ConfigureAwait(false);
var report = _excelExporter.Export(entites.OrderByDescending(d => d.Date));
return File(report, MimeTypes.GetMimeType("excel.xlsx"), $"entities.xlsx");
}
生成Excel电子表格是通过内存流完成的。以下是我开始创建excel文件的几行内容:
using (MemoryStream mem = new MemoryStream())
{
using (var document = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook))
{
var workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Report"
};
sheets.Append(new[] { sheet });
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
var row = new Row();
// This needs to get adjusted for your needs
// it returns IEnumerable<Cell>
row.Append(GenerateHeaderCells(/*FillMe*/));
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
foreach (var entity in data)
{
row = new Row();
//This needs to get adjusted
// it returns IEnumerable<Cell>
row.Append(GenerateCells(/*FillMe*/));
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
return mem.ToArray();
}
答案 1 :(得分:0)
我的系统上没有安装MS-Office,我的要求是生成文件并将其发送到电子邮件。因此,最终目标是将excel发送给管理员用户。当我编写代码以将其发送到电子邮件并检查电子邮件时,excel会显示数据,但是当我从同一代码返回数据时,它是空白表。也许我应该使用互操作的dll。