C#, CSV,Generic, 泛型,导出

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;

namespace ConsoleApp317
{
class Program
{
static string csvFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".csv";
static string logFileName =".\\"+ DateTime.Now.ToString("yyyyMMdd") + "log.txt";
static Stopwatch stopWatch = new Stopwatch();
static string exportMsg="";
[STAThread]
static void Main(string[] args)
{
using (AdventureWorks2017Entities context = new AdventureWorks2017Entities())
{
List<SalesOrderDetail> orderList = context.SalesOrderDetails.ToList();
orderList.AddRange(orderList);
orderList.AddRange(orderList);
orderList.AddRange(orderList);
orderList.AddRange(orderList);
ExportByCSV<SalesOrderDetail>(orderList);
}

MessageBox.Show(exportMsg);

Console.ReadLine();
}

static void ExportByCSV<T>(List<T> dataList)
{
StringBuilder exportBuilder = new StringBuilder();
if (dataList==null && !dataList.Any())
{
return;
}

using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.FileName = csvFileName;
sfd.Filter = "Csv Files|*.csv|All Files|*.*";

if(sfd.ShowDialog()==DialogResult.OK)
{
stopWatch.Start();
var firstRowData = dataList.FirstOrDefault();
var properties = firstRowData.GetType().GetProperties().Where(x => !x.GetMethod.IsVirtual).ToList();
exportBuilder.Append(string.Join(",", properties.Select(x => x.Name))+Environment.NewLine);
foreach (var dl in dataList)
{
for (int i = 0; i < properties.Count() - 1; i++)
{
var prop = properties[i];
exportBuilder.Append(prop.GetValue(dl) + ",");
}
exportBuilder.Append(properties[properties.Count - 1].GetValue(dl) + Environment.NewLine);
}

using (StreamWriter writer = new StreamWriter(sfd.FileName))
{
writer.WriteLine(exportBuilder.ToString());
}

stopWatch.Stop();
exportMsg = $"There are {dataList.Count} rows data and cost {stopWatch.ElapsedMilliseconds} milliseconds";
File.AppendAllText(logFileName, exportMsg+Environment.NewLine);
}
}
}
}
}

原文链接: https://www.cnblogs.com/Fred1987/p/10263602.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C#, CSV,Generic, 泛型,导出

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/402245

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:40
下一篇 2023年4月19日 上午9:40

相关推荐