c#保存数据格式为.cvs_C#保存数据为CSV文件、Excel文档

这段代码展示了如何使用C#来创建并保存数据到CSV文件中。它首先检查数据文件根路径是否存在,然后创建一个StringBuilder对象来构建列标题和行数据。文件名基于当前日期时间,文件以UTF-8编码写入,如果文件已存在,则追加数据,否则新建文件并写入数据。
摘要由CSDN通过智能技术生成

1 public void WriteData()

2 {

3 try

4 {

5 if (System.IO.Directory.Exists(DataFileRootPath) == false)

6 {

7 System.IO.Directory.CreateDirectory(DataFileRootPath);

8 }

9 StringBuilder DataColumn = new StringBuilder();

10 StringBuilder DataLine = new StringBuilder();

11

12 string strT = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();

13

14 //列标题

15 DataColumn.Append("DateTime,");

16 //行数据

17 DataLine.Append(strT + ",");

18

19

20

21

22 string FileName = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();

23 string FilePath = DataFileRootPath + "\\" + FileName + ".CSV";

24

25 if (System.IO.File.Exists(FilePath) == false)

26 {

27 System.IO.StreamWriter stream = new System.IO.StreamWriter(FilePath, false, Encoding.UTF8);

28 stream.WriteLine(DataColumn);

29 stream.WriteLine(DataLine);

30 stream.Flush();

31 stream.Close();

32 stream.Dispose();

33 }

34 else

35 {

36 System.IO.StreamWriter stream = new System.IO.StreamWriter(FilePath, true, Encoding.UTF8);

37 stream.WriteLine(DataLine);

38 stream.Flush();

39 stream.Close();

40 stream.Dispose();

41 }

42 }

43 catch (Exception ex)

44 {

45

46 }

47 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值