将对象列表转换为可读性良好的CSV/Excel文件



我有两个类,如下所示:

public class SortedUser
{
public string Email { get; set; }
public List<IpInfo> IPAndCountries = new List<IpInfo>();
}

然后:

public class IpInfo
{
public string Ip { get; set; }

public string Hostname { get; set; }

public string City { get; set; }

public string Region { get; set; }

public string Country { get; set; }

public string Loc { get; set; }

public string Org { get; set; }

public string Postal { get; set; }
}

我想从中创建一个可读性合理的文件(txt,csv,甚至xls/xlsx(,看起来像

User1 Email
IP1 Country City
IP2 Country City
IP3 Country City
and so on...
User2 Email
IP1 Country City
IP2 Country City
IP3 Country City
and so on...
User3 Email
IP1 Country City
IP2 Country City
IP3 Country City
and so on...

执行此操作最简单的方法是什么?有人能帮我吗?

附言:它甚至可以是PDF文件(这将是最好的(。

尝试以下操作:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:temptest.csv";
static void Main(string[] args)
{
SortedUser sortedUser = new SortedUser();
sortedUser.Output(FILENAME);
}
}
public class SortedUser
{
public static List<SortedUser> sortedUsers = new List<SortedUser>();
public string Email { get; set; }
public List<IpInfo> IPAndCountries = new List<IpInfo>();
public void Output(string filename)
{
StreamWriter writer = new StreamWriter(filename);
string line = "";

line = string.Join(",",new string[] {"Email","Ip","Hostname", "City", "Region", "Country", "Loc", "Org", "Postal"});
writer.WriteLine(line);
foreach (SortedUser user in sortedUsers)
{
foreach (IpInfo ipInfo in user.IPAndCountries)
{
line = string.Join(",",
user.Email,
ipInfo.Ip,
ipInfo.Hostname,
ipInfo.City,
ipInfo.Region,
ipInfo.Country,
ipInfo.Loc,
ipInfo.Org,
ipInfo.Postal
);
writer.WriteLine(line);
}
}
writer.Flush();
writer.Close();
}
}

public class IpInfo
{
public string Ip { get; set; }
public string Hostname { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string Loc { get; set; }
public string Org { get; set; }
public string Postal { get; set; }
}
}

最新更新