欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#保存数据为CSV文件、Excel文档

程序员文章站 2024-01-08 21:02:28
1 public void WriteData() 2 { 3 try 4 { 5 if (System.IO.Directory.Exists(DataFileRootPath) == false) 6 { 7 System.IO.Directory.CreateDirectory(DataFil ......
C#保存数据为CSV文件、Excel文档
 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         }
View Code

 

上一篇:

下一篇: