gpt4 book ai didi

c# - 如何利用 StreamWriter 写入 csv 文件?

转载 作者:行者123 更新时间:2023-11-30 19:07:23 25 4
gpt4 key购买 nike

这就是我正在处理的内容。我正在尝试获取一个 XML 文件,从属性中提取信息,将它们附加在一起,然后将其写入 CSV 文件。我对编程还比较陌生,另一个程序员今天不在办公室,所以我真的需要一些帮助。

我的第一个问题是关于 StringBuilder。我是否需要在我的 StringBuilder 末尾有一个 AppendLine,以便 foreach 循环输出的每个字符串都在一个新行上?我是否需要在 foreach 循环中执行此操作?

我的第二个问题是关于将我的字符串实际写入 CSV 文件。它看起来像吗?

swOutputFile.WriteLine(strAppendedJobData)

而且我认为这也会进入 foreach 循环,但我不太确定。

感谢您的帮助,我希望我的问题措辞简单易懂。

//Create a stream writer to write the data from returned XML job ticket to a new CSV
StreamWriter swOutputFile;
string strComma = ",";
swOutputFile = new StreamWriter(new FileStream("C:\\Dev\\AppendedJobData.csv", FileMode.Create, FileAccess.Write, FileShare.Read));

//Get nodes from returned XML ticket
XmlNodeList xmlJobs = xdResults.SelectNodes("/Updates/Jobs/Job");
//Pull out data from XML attributes
foreach (XmlElement xeJobUpdate in xmlJobs)
{
//Break down the job data
string strProjectID = xeJobUpdate.GetAttribute("SharpOwlProjectID");
string strJobNumber = xeJobUpdate.GetAttribute("JobNumber");
string strClientCode = xeJobUpdate.GetAttribute("SharpOwlClientCode");
string strClient = xeJobUpdate.GetAttribute("Client");
string strVCAOffice = xeJobUpdate.GetAttribute("VCAOffice");
string strLoadStatus = xeJobUpdate.GetAttribute("LoadStatus");

//Build the string to be added to the new CSV file

StringBuilder sbConcatJob = new StringBuilder();
sbConcatJob.Append(strProjectID).Append(strComma).Append(strJobNumber)
.Append(strComma).Append(strClientCode).Append(strComma).Append(strClient).Append(strComma)
.Append(strVCAOffice).Append(strComma).Append(strLoadStatus).Append(strComma);
string strAppendedJobData = sbConcatJob.ToString();

最佳答案

如果你想做得更优雅一点,你可以这样做:

 using(StreamWriter swOutputFile = new StreamWriter(new FileStream("C:\\Dev\\AppendedJobData.csv", FileMode.Create, FileAccess.Write, FileShare.Read)))
{
//Get nodes from returned XML ticket
XmlNodeList xmlJobs = xdResults.SelectNodes("/Updates/Jobs/Job");
//Pull out data from XML attributes
foreach (XmlElement xeJobUpdate in xmlJobs)
{
List<String> lineItems = new List<String>();
lineItems.add(xeJobUpdate.GetAttribute("SharpOwlProjectID"));
//add all the other items

swOutputFile.WriteLine(String.Join(',', myLine.ToArray()));



}
//after the loop you close the writer
}

//all the work is done much easier

关于c# - 如何利用 StreamWriter 写入 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6073942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com