我在 VS2005 中工作,我需要 C# 语法 write 来在 Excel 工作表中写入集合值。我这样初始化集合:
Reports oReports =new Reports();//oReports is a collection
假设这个集合有值,我该如何将它们写入 Excel?
请您参考如下方法:
如果您不想花时间学习如何写入 Excel,您可以做一些快速而肮脏的事情 - 只需写入一个 .csv 文件,自己在 excel 中打开它并另存为 Excel 格式。
只需在流中输出,例如:(如果您的报告值中也包含逗号,则可以使用)
using (StreamWriter sw = new StreamWriter(@"C:\file.csv"))
{
StringBuilder csvLine = new StringBuilder();
//Enter your header row here:
csvLine.Append("Header1,Header2,Header3");
sw.WriteLine(csvLine.ToString());
foreach (Report report in Reports)
{
csvLine = new StringBuilder();
csvLine.Append(string.Format("\"{0}\",", report.Value1));
csvLine.Append(string.Format("\"{0}\",", report.Value2));
csvLine.Append(string.Format("\"{0}\"", report.Value3)); //etc
sw.WriteLine(csvLine.ToString());
}
sw.Flush();
}
