C++ 数据保存到xls中

C++ 数据保存到xls中

1.将数据保存至当前执行目录下:

CFile file;
int nData1 = 100;//这里只是简单的将nData1和nData2数据保存到xls文件中
int nData2 = 200;
CString msg;
	
TCHAR szPath[MAX_PATH];//获取路径信息
::GetModuleFileName(AfxGetApp()->m_hInstance, szPath, MAX_PATH);
CString szExeFilePath = szPath;
int index = szExeFilePath.ReverseFind('\\');
szExeFilePath = szExeFilePath.Left(index + 1);
CString fileName = szExeFilePath + strRptTime + ".xls";//保存在执行目录下

CTime time = CTime::GetCurrentTime();//获取当前时间
CString strRptTime = time.Format("%Y%m%d%H%M%S");

CString fileName = szExeFilePath + strRptTime + ".xls";//保存在执行目录下
if (!file.Open(fileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive))
{
    
    
	file.Close();
	return;
}
msg.Format("%d\t%d\n", nData1 , nData12);
file.Write(msg, msg.GetLength());
file.close();

2.定位到最后一行(添加多行数据时会用到):

file.SeekToEnd();//

2.文件的关闭(可放到析构函数中,退出时进行文件关闭)

if (file.m_hFile != CFile::hFileNull)//检测文件是否打开
{
    
    
		file.Close();
}

CFile类的成员变量:
m_hFile:表示一个打开文件的操作系统文件句柄。通过对m_hFile 与 CFile::hFileNull的比较来判断该文件是否已经打开。

还可以利用file.GetFileName().IsEmpty()来判断

 if (!file.GetFileName().IsEmpty())
 6     {
    
    
 7         file.Close();
 8     }

猜你喜欢

转载自blog.csdn.net/CXYLVCHF/article/details/111748257