在我的asp.net应用程序中,我让用户通过单击按钮从视图中导出一些数据。下面的代码导出一个excel文件。问题是我无法弄清楚如何显示对象的模型列表。
var grid = new GridView();
grid.DataSource = exportModels;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Exported_Orders.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
数据源模型是:
public class ExportOrdersViewModel
{
public int Id { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
public string CustomerEmail { get; set; }
public string CustomerMobile { get; set; }
public string ShippingStreet { get; set; }
public string ShippingCity { get; set; }
public string ShippingCountry { get; set; }
public string ShippingPostalCode { get; set; }
public string ShippingTo { get; set; }
public bool IsShipped { get; set; }
public ICollection<ExportOrdersItemViewModel> Items { get; set; }
}
public class ExportOrdersItemViewModel
{
public string TicketName { get; set; }
public string EventName { get; set; }
public int Quantity { get; set; }
public string CurrencyId { get; set; }
public string PaymentCurrencyId { get; set; }
public string UnitPrice { get; set; }
public string PaymentUnitPrice { get; set; }
}
ExportOrderViewModel包含ExportOrderItemViewModel列表,当导出文件时,该文件中缺少每个订单的项目行。我真的需要一些关于如何在导出时添加这些字段的帮助。
以下是导出文件的标题:
答案 0 :(得分:1)
正如@Crowcoder建议的那样,我使用了CLoseXML库,最终成功地找到了解决问题的方法。
这是生成我想要的Excel的代码
using (var workBook = new XLWorkbook())
{
var workSheet = workBook.Worksheets.Add("Guests");
var guestTable = new DataTable();
guestTable.Columns.Add(Resources.Strings.FirstName, typeof(string));
guestTable.Columns.Add(Resources.Strings.LastName, typeof(string));
guestTable.Columns.Add(Resources.Strings.TicketName, typeof(string));
guestTable.Columns.Add(Resources.Strings.TicketType, typeof(string));
guestTable.Columns.Add(Resources.Strings.ShortCode, typeof(string));
guestTable.Columns.Add(Resources.Strings.HasVisitorEnteredEvent, typeof(string));
foreach (var entry in guestList)
{
guestTable.Rows.Add(
entry.FirstName,
entry.LastName,
entry.TicketName,
entry.TicketType,
entry.ShortCode,
entry.HasEntered);
}
workSheet.Cell(1, 1).InsertTable(guestTable);
workSheet.Tables.ForEach(t => t.ShowAutoFilter = false);
workSheet.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
workSheet.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
workSheet.Tables.ForEach(t => t.Theme = XLTableTheme.TableStyleLight13);
workSheet.Columns().AdjustToContents();
workBook.SaveAs(outputStream);
}