简体   繁体   English

在C#中使用StreamWriter时,请编写以.csv或Excel文件分隔的其他选项卡或文件

[英]Write different tab or files separated in .csv or Excel file when using StreamWriter in C#

I have a console application that outputs the result into a .csv file. 我有一个控制台应用程序,可将结果输出到.csv文件中。 The console application calls several web services and outputs several data. 控制台应用程序调用多个Web服务并输出多个数据。 The output contain URLs which differentiate one site from another other. 输出包含将一个站点与另一个站点区分开的URL。 The code works fine, but the output is in one big CSV file and it gets divided when it reaches the header then starts writing the data from the new site. 该代码可以正常工作,但是输出在一个大CSV文件中,当到达标头时它将被分割,然后开始从新站点写入数据。

Here you have how the output is now from the CSV file: 这里是CSV文件现在的输出方式:

ProjectTitle,PublishStatus,Type,NumberOfUsers, URL
Project one,published,Open,1,http://localhost/test1
Project two,expired,Closed,14,http://localhost/test1

ProjectTitle,PublishStatus,Type,NumberOfUsers,URL
Project one V2,expired,Closed,2,http://localhost/test2
Project two V2,Published,Open,3,http://localhost/test2

What I am trying to do its to either output the first set of data (depending on each URL) and then the second set of data in a different tab in Excel, or just create a new file for the new set of data. 我要执行的操作是输出第一组数据(取决于每个URL),然后输出第二组数据在Excel中的其他选项卡中,或者仅为新数据集创建一个新文件。 My code: 我的代码:

public static XmlDocument xml = new XmlDocument();

static void Main(string[] args)
{
    xml.Load("config.xml");
    test();            
}

private static void test()
{

List<string> url = new List<string>();
int count = xml.GetElementsByTagName("url").Count;

for (int i = 0; i < count; ++i)
{
    url.Add(xml.GetElementsByTagName("url")[i].InnerText);

    Url = url[i];               

}

string listFile = "ListOfSites";
string outCsvFile = string.Format(@"C:\\testFile\\{0}.csv", testFile + DateTime.Now.ToString("_yyyyMMdd HHmms"));


using (FileStream fs = new FileStream(outCsvFile, FileMode.Append, FileAccess.Write))                    
using (StreamWriter file = new StreamWriter(fs))

file.WriteLine("ProjectTitle,PublishStatus,Type,NumberOfSUsers,URL");
    foreach(WS.ProjectData proj in pr.Distinct(new ProjectEqualityComparer()))
        {
            file.WriteLine("{0},\"{1}\",{2},{3},{4}",
            proj.ProjectTitle,                               
            proj.PublishStatus,                               
            proj.type,
            proj.userIDs.Length.ToString(NumberFormatInfo.InvariantInfo),
            url[i].ToString());
        }
}

This is a quick fix. 这是一个快速修复。 There may be a more elegant way to accomplish this as well: 可能还有一种更优雅的方法可以完成此操作:

public static XmlDocument xml = new XmlDocument();

static void Main(string[] args)
{
    xml.Load("config.xml");

    // relocated from `test` method to `Main`
    List<string> url = new List<string>();
    int count = xml.GetElementsByTagName("url").Count;

    for (int i = 0; i < count; ++i)
    {
        url.Add(xml.GetElementsByTagName("url")[i].InnerText);

        Url = url[i];               
        test(Url);
    }

}

private static void test(string url)
{
    string listFile = "ListOfSites";
    string outCsvFile = string.Format(@"C:\\testFile\\{0}.csv", testFile + DateTime.Now.ToString("_yyyyMMdd HHmms"));


    using (FileStream fs = new FileStream(outCsvFile, FileMode.Append, FileAccess.Write))           
    {
        using (StreamWriter file = new StreamWriter(fs))
        {
            file.WriteLine("ProjectTitle,PublishStatus,Type,NumberOfSUsers,URL");
        foreach(WS.ProjectData proj in pr.Distinct(new ProjectEqualityComparer()))
            {
                file.WriteLine("{0},\"{1}\",{2},{3},{4}",
                proj.ProjectTitle,                               
                proj.PublishStatus,                               
                proj.type,
                proj.userIDs.Length.ToString(NumberFormatInfo.InvariantInfo),
                url);
            }
        }
    }         
}

NOTE: Please use braces in C# even if you don't NEED them. 注意:即使不需要,也请在C#中使用花括号。 It makes your code more readable. 它使您的代码更具可读性。

If you want to write an Excel file with different worksheets you can try and use the EpPlus library, it is open source and free. 如果要使用不同的工作表编写Excel文件,则可以尝试使用EpPlus库,该库是开源的且免费的。

Here is the nuget page 这是nuget页面

To generate more files, you have to decide how to name them and if the records for each file are random in the source list, you can generate different lists of output strings for different output files and use the File.AppendAllLines(filename, collection); 要生成更多文件,必须决定如何命名它们,并且如果每个文件的记录在源列表中是随机的,则可以为不同的输出文件生成不同的输出字符串列表,并使用File.AppendAllLines(filename,collection) ; to save the data in the different files. 将数据保存在不同的文件中。 I don't recommend you to open and close the files for each row to write because it is a time and resource consuming operation. 我不建议您打开和关闭要写的每一行的文件,因为这是耗时和资源的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM