MFC 数据项写入CSV文件

 


//将数据项写入CSV文件
int PutCSVItemLine(FILE *file, CStringArray &sItemLine)
{
  //准备行数据
  CStringA sLineString;

  //循环取子项
  for(INT_PTR nItem=0; nItem= 0)
    {
      //单引号替换为双引号
      sItem.Replace("\"", "\"\"");

      //首尾用引号包含
      sItem.Insert(0, "\""); sItem += "\"";
    }

    //添加逗号分隔符
    if(!sLineString.IsEmpty()) sLineString += ",";

    //追加数据
    sLineString += sItem;
  }

  //行尾添加\r\n
  sLineString += "\r\n";

  //写入文件
  return (int) fwrite((LPCSTR)sLineString, 1, sLineString.GetLength(), file);
  
}
//应用实例
void TestCSV()
{
  FILE *f = NULL;
  if(_tfopen_s(&f, _T("E:\\TEMP\\test.csv"), _T("wb")) == 0)
  {
    {
      CStringArray sLine;
      sLine.Add(_T("1"));
      sLine.Add(_T("\"2\""));
      sLine.Add(_T("3,ABC"));
      sLine.Add(_T("4"));
      sLine.Add(_T("\"\""));
      sLine.Add(_T(","));
      sLine.Add(_T("\",\""));
      sLine.Add(_T(""));
      sLine.Add(_T("aaa\",\"bbb"));

      PutCSVItemLine(f, sLine);
    }

    {
      CStringArray sLine;
      sLine.Add(_T("1"));
      sLine.Add(_T("\"2\""));
      sLine.Add(_T("3,ABC"));
      sLine.Add(_T("4"));
      sLine.Add(_T("\"\""));
      sLine.Add(_T(","));
      sLine.Add(_T("\",\""));
      sLine.Add(_T(""));
      sLine.Add(_T("aaa\"??bbb\""));

      PutCSVItemLine(f, sLine);
    }


    fclose(f);
  }
}

输出文件内容

1,"""2""","3,ABC",4,"""""",",",""",""",,"aaa"",""bbb"
1,"""2""","3,ABC",4,"""""",",",""",""",,"aaa""??bbb"""
 

你可能感兴趣的:(其它,文档/视,算法)