Export the content of the list box in MFC as data, support excel and Txt format

Export the content of the list box in MFC as data, support excel and Txt format

This code supports export in Excel and Txt, and the custom name is the current date and time when exporting, which can be modified

void CHMList::OnBnClickedButtondataout()
{
    
    
	// TODO: 在此添加控件通知处理程序代码
	CTime m_time;
	m_time=CTime::GetCurrentTime();//获取系统当前时间
	CString m_strDateTime;//系统时间
	m_strDateTime=m_time.Format("%Y.%m.%d");//系统时间格式化,以年月日方式
	if (m_list.GetItemCount() <= 0)   
	{
    
    
		AfxMessageBox(_T("列表中没有数据,无法导出"));
		return;
	}
	char szFilters[] = _T("xlsx文件(*.xlsx)|*.xlsx|txt文件(*.txt)|*.txt|所有文件(*.*)|*.*||");
	CFileDialog dlg(FALSE, _T("xlsx"),m_strDateTime, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilters, this);
	if (dlg.DoModal() != IDOK)
		return;
	CString strFilePath;
	strFilePath = dlg.GetPathName();//获得文件路径名
	DWORD dwRe = GetFileAttributes(strFilePath);
	if (dwRe != (DWORD)-1)
	{
    
    
		DeleteFile(strFilePath);
	}
	//保存文件数据
	FILE*fp;
	fopen_s(&fp, strFilePath, "w");
	//	char str[1024];
	if (fp == NULL)
	{
    
    
		printf("save file error\n");
		return;
	}
	//得到listctrl的所有列的header字符串内容
	int nHeadNum = m_list.GetHeaderCtrl()->GetItemCount();
	LVCOLUMN lvcol;
	char str_out[256];
	int nColNum;
	nColNum = 0;
	lvcol.mask = LVCF_TEXT;
	lvcol.pszText = str_out;
	lvcol.cchTextMax = 256;
	while (m_list.GetColumn(nColNum, &lvcol))
	{
    
    
		nColNum++;
		fprintf_s(fp, "%s\t", lvcol.pszText);
	}
	fprintf_s(fp, "\n", lvcol.pszText);

	//读取listctrl数据

	int nRow = m_list.GetItemCount();
	for (int i = 0; i < nRow; i++)
	{
    
           
		for(int j=0;j<nColNum;j++)

		{
    
    
			CString str_data = m_list.GetItemText(i,j);//获取指定列
			fprintf_s(fp, "%s\t", str_data);  // \t为水平制表符
		}
		fprintf_s(fp, "\n");
	}
	fclose(fp);
	AfxMessageBox("文件已生成!");
}

The effect is shown in the figure: Is
Insert picture description here
this saving method great? It is the same as directly using the computer to operate on the computer

Guess you like

Origin blog.csdn.net/weiwei_lol/article/details/109271959