C#中关于CSV文件的写入和读取
2021-01-30 07:12
标签:for har adc buffer dex 文件的 cells false 地址 --------------------------------------------------------------------------------------------------- /// private static List ------------------------------------------------------------ 有点乱,凑合看 C#中关于CSV文件的写入和读取 标签:for har adc buffer dex 文件的 cells false 地址 原文地址:https://www.cnblogs.com/ysydave/p/11669165.html
///
/// 保存CSV文档
///
/// 地址
/// 內容
/// 是否覆蓋保存,false覆盖
public static void WriteCSV(string filePathName, List
{
StreamWriter fileWriter=new StreamWriter(filePathName,append,Encoding.Default);
foreach (string[] cells in rows)
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i {
string str = cells[i].Replace("\"", "").Trim();
if (str == null)
str = "";
if(str.IndexOf(",")>-1){
str = "\""+str+"\"";
}
buffer.Append(str);
if (i != cells.Length - 1)
buffer.Append(quotechar);
}
fileWriter.WriteLine(buffer.ToString());
}
fileWriter.Flush();
fileWriter.Close();
}
/// 讀取文檔文件
///
/// 地址
///
public static List
{
StreamReader fileReader = new StreamReader(filePathName, Encoding.Default);
string rowStr = fileReader.ReadLine();
// "a,1",b,c // "\"a,1\",\"b,1,2\",\"c,cc\",ddd"
List
while (rowStr != null) {
List
string[] cells = new string[cellVals.Count];
for (int i = 0; i cells[i] = cellVals[i];
}
rowList.Add(cells);
rowStr = fileReader.ReadLine();
}
fileReader.Close();
return rowList;
}
List
while (rowStr != null && rowStr.Length > 0)
{
string cellVal = "";
if (rowStr.StartsWith("\""))
{
rowStr = rowStr.Substring(1);
int i = rowStr.IndexOf("\",");
int j = rowStr.IndexOf("\" ,");
int k = rowStr.IndexOf("\"");
if (i if (i if (i > -1)
{
cellVal = rowStr.Substring(0, i);
if ((i + 2) rowStr = rowStr.Substring(i + 2).Trim();
else
rowStr = "";
}
else
{
cellVal = rowStr;
rowStr = "";
}
}
else
{
int i = rowStr.IndexOf(",");
if (i > -1)
{
cellVal = rowStr.Substring(0, i);
if ((i + 1) rowStr = rowStr.Substring(i + 1).Trim();
else
rowStr = "";
}
else
{
cellVal = rowStr;
rowStr = "";
}
}
if (cellVal == "") cellVal = " ";
cellList.Add(cellVal);
}
return cellList;
}