CSV文件读写

31 篇文章 7 订阅
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;
		} 
	}
}

结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随心漂流

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值