写
void CcsvWriteDlg::WriteCsv()
{
CString strFilePath = _T("D:\\DataCsv.csv");
CFileFind finder;
//判断文件是否存在,存在返回true,不存在返回false
BOOL bWorking = (bool)finder.FindFile(strFilePath);
if (!bWorking)
{
//不存在,创建
if (CStdioFile *fsp = new CStdioFile(strFilePath, CFile::modeCreate))
{
fsp->Close();
delete fsp;
}
}
try
{
if (CStdioFile *fsp = new CStdioFile(strFilePath, CFile::shareDenyNone | CFile::modeWrite || CFile::modeCreate | CFile::modeNoTruncate))
{
fsp->SeekToEnd();
COleDateTime t = COleDateTime::GetCurrentTime();
CString str;
str.Format(
_T("Product")
_T(",20")
_T(",%d/%d/%d")
_T(",66")
_T("\n")
, t.GetDay(), t.GetMonth(), t.GetYear()
);
fsp->WriteString(str);//每个单元格以逗号隔开,每次写完一整行
fsp->Close();
delete fsp;
}
}
catch (CFileException* e)
{
switch (e->m_cause)
{
case CFileException::fileNotFound:
{
AfxMessageBox(_T("找不到.csv文件!)"));
e->Delete();//删除异常对象
break;
}
case CFileException::invalidFile:
{
AfxMessageBox(_T("打开.csv文件时发生异常!)"));
e->Delete();
break;
}
default:
break;
}
}
}
结果:
读
void CcsvWriteDlg::ReadCsv()
{
//读取内容
CString strFilePath = _T("D:\\DataCsv.csv");
try
{
if (CStdioFile *fsp = new CStdioFile(strFilePath, CFile::shareDenyNone | CFile::modeRead))
{
CString str;
while (fsp->ReadString(str))//每次读一整行
{
//去掉首尾空格
str = str.Trim(_T(" "));
CString substr[4];
int count = 0;
int index = str.Find(_T(","));
while (index != -1 && count < 4)
{
substr[count++] = str.Left(index); //截取每个单元格(,)左边的内容,保存到substr[]里
str = str.Right(str.GetLength() - index - 1);
index = str.Find(_T(",")); //数据列以逗号分隔,每一行数据都以回车符结束
if (count == 3)
{
//最后一个数据
substr[count++] = str;
}
}
}
fsp->Close();
delete fsp;
}
}
catch (CFileException* e)
{
switch (e->m_cause)
{
case CFileException::fileNotFound:
{
AfxMessageBox(_T("找不到.CSV文件!"));
e->Delete();//删除异常对象
break;
}
case CFileException::invalidFile:
{
AfxMessageBox(_T("打开csv文件时发生异常!)"));
e->Delete();
break;
}
default:
break;
}
}
}
结果: