我尝试导出一个名为table的HTML表,该表动态绑定到C#中的ViewData.Model。我有一个名为export的方法,它是根据另一个方法的操作调用的。所以在那之前的一切都已经准备好了..我只是不知道如何将数据导出为CSV或Excel文件。因此,当I步入Export方法时,我不知道下一步如何导出表。有人能帮帮我吗?
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}发布于 2009-01-12 00:48:36
我不太理解“导出一个动态绑定到ViewData.Model的名为table的超文本标记语言表”的全部内容,所以我将忽略它,只关注Export(List list)方法。顺便说一句,你从来没有真正提到哪里出了问题,哪里出了问题。
我看到你写了“如果他们有Excel导出到excel,如果没有导出到csv”-我个人会在这两种情况下都将其导出为CSV文件,因为excel可以处理csv文件没有问题。
考虑到这一点,下面是我基于您的代码的导出方法。
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}https://stackoverflow.com/questions/429588
复制相似问题