繁体   English   中英

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

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

我有一个控制台应用程序,可将结果输出到.csv文件中。 控制台应用程序调用多个Web服务并输出多个数据。 输出包含将一个站点与另一个站点区分开的URL。 该代码可以正常工作,但是输出在一个大CSV文件中,当到达标头时它将被分割,然后开始从新站点写入数据。

这里是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

我要执行的操作是输出第一组数据(取决于每个URL),然后输出第二组数据在Excel中的其他选项卡中,或者仅为新数据集创建一个新文件。 我的代码:

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());
        }
}

这是一个快速修复。 可能还有一种更优雅的方法可以完成此操作:

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);
            }
        }
    }         
}

注意:即使不需要,也请在C#中使用花括号。 它使您的代码更具可读性。

如果要使用不同的工作表编写Excel文件,则可以尝试使用EpPlus库,该库是开源的且免费的。

这是nuget页面

要生成更多文件,必须决定如何命名它们,并且如果每个文件的记录在源列表中是随机的,则可以为不同的输出文件生成不同的输出字符串列表,并使用File.AppendAllLines(filename,collection) ; 将数据保存在不同的文件中。 我不建议您打开和关闭要写的每一行的文件,因为这是耗时和资源的操作。

暂无
暂无

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

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