VC之CSV文件操作

CSV文件格式

CSV即Comma Separate Values,这种文件格式经常用来作为不同程序之间的数据交互的格式。


具体文件格式:
每条记录占一行 
以逗号为分隔符 
逗号前后的空格会被忽略 
字段中包含有逗号,该字段必须用双引号括起来 
字段中包含有换行符,该字段必须用双引号括起来 
字段前后包含有空格,该字段必须用双引号括起来 
字段中的双引号用两个双引号表示 
字段中如果有双引号,该字段必须用双引号括起来 
第一条记录,可以是字段名


下面简单介绍下CSV文件的操作。


首先,新建对话框应用程序,添加文件操作按钮。


头文件

private:
	void WriteCsvContent();
	CStdioFile m_File;

源文件

void CCreateCsvFileDlg::OnButton1() 
{
	//获取系统时间
	SYSTEMTIME SystemTime;
	::GetLocalTime(&SystemTime);
	CString str="",Date="";
	str.Format("%02d",SystemTime.wYear);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wMonth);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wDay);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wHour);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wMinute);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wSecond);
	Date = Date + str;

	//获取当前路径
	CString sCurrentPath = "";
	char Path[270];
	DWORD len = 0;
	DWORD i=0;
	len = GetCurrentDirectory(270,Path);
	for (i=0; i<len; i++)
	{
		sCurrentPath = sCurrentPath + CString(Path[i]);
	}

	//创建文件
	CString sFilePathName = "";
	sFilePathName = sCurrentPath + "\\MyFile" + "_" + Date + ".csv";
	//打开
	CFileException ex;
	if(!m_File.Open(sFilePathName,CFile::modeCreate | CFile::modeWrite | CFile::typeText,&ex))
	{
		ex.ReportError();
		return;
	}
	//写入
	WriteCsvContent();
	//关闭
	m_File.Close();
	
	MessageBox("创建CSV文件成功!","提示框",MB_OK | MB_ICONWARNING);

}

void CCreateCsvFileDlg::WriteCsvContent()
{
	CString str = "";
	CString sline = "";
	
	//数据头
	str = "序号";
	sline = str + ",";
	str = "名称";
	sline = sline + str + ",";
	str = "年龄";
	sline = sline + str + ",";
	sline = sline + "\n";
	m_File.WriteString(sline);
	
	//数据内容
	str = "001";
	sline = str + ",";
	str = "小明";
	sline = sline + str + ",";
	str = "18";
	sline = sline + str + ",";
	sline = sline + "\n";
	m_File.WriteString(sline);

	str = "002";
	sline = str + ",";
	str = "小红";
	sline = sline + str + ",";
	str = "17";
	sline = sline + str + ",";
	sline = sline + "\n";
	m_File.WriteString(sline);

	str = "003";
	sline = str + ",";
	str = "小华";
	sline = sline + str + ",";
	str = "19";
	sline = sline + str + ",";
	sline = sline + "\n";
	m_File.WriteString(sline);
}

运行效果



点击创建CSV文件按钮



找到生成的文件



用记事本打开



用excel打开




相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页