/// <summary>
/// csv文件数据保存
/// </summary>
/// <param name="FullPath"></param>
/// <param name="ArrayData"></param>
/// <returns></returns>
public static bool SaveCSVData(string FullPath, string dataStr)
{
StringBuilder DataColumn = new StringBuilder();
StringBuilder DataLine = new StringBuilder();
string currentTime = System.DateTime.Now.ToString(); // 当前时间
string SN = "SN"; // 二维码
//列标题
DataColumn.Append("SN,DateTime,data1,data2,data3,");
//行数据
DataLine.Append(SN +"," + currentTime + "," + dataStr + ",");
string FilePath = Application.StartupPath + FullPath + ".CSV"; ;
if (System.IO.File.Exists(FilePath) == false)
{
// 如果表格不存在,则创建表格
System.IO.StreamWriter stream = new System.IO.StreamWriter(FilePath, false, Encoding.UTF8);
stream.WriteLine(DataColumn); // 列标题
stream.WriteLine(DataLine); //行数据
stream.Flush();
stream.Close();
stream.Dispose();
}
else
{
// 若表格存在,直接存储数据
System.IO.StreamWriter stream = new System.IO.StreamWriter(FilePath, true, Encoding.UTF8);
stream.WriteLine(DataLine); //行数据
stream.Flush();
stream.Close();
stream.Dispose();
}
return true;
}
// 测试使用-1
string dataStr= "10,20,30";
SaveCSVData("/test", dataStr);
// 测试使用-2
string dataStr2="";
for (int i = 0; i < 3; i++)
{
dataStr2 += i.ToString()+","; // ToString(),将数字转化为字符串
}
SaveCSVData("/test", dataStr2);