假设你的listContrl控件的变量为m_Listctrl,那么,参考以下代码:
void Cxxx::ListExport()
{
int item_count=m_ListCtrl.GetItemCount();
if (item_count==0)
{
MessageBox(_T("列表为空时不能导出。"),_T("警告"),MB_OK|MB_ICONEXCLAMATION);
return;
}
OPENFILENAME *ofn=new OPENFILENAME;
TCHAR szFile[MAX_PATH];
ZeroMemory(szFile,sizeof(szFile)/sizeof(TCHAR));
ZeroMemory(ofn,sizeof(OPENFILENAME));
ofn->lStructSize=sizeof(OPENFILENAME);
ofn->hwndOwner = m_hWnd;
ofn->lpstrFile = szFile;
ofn->lpstrFile[0] = _T('\0');
ofn->nMaxFile = sizeof(szFile);
ofn->lpstrFilter = _T("文本文件\0*.txt\0");
ofn->nFilterIndex = 1;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
ofn->lpstrInitialDir = _T("Record//");
ofn->Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
CString strFile;
// 显示打开选择文件对话框。
if ( GetSaveFileName(ofn))
{
//显示选择的文件。
strFile.Format(_T("%s"),szFile);
}else
{
return;
}
delete ofn;
ofn=NULL;
CString tmp;
int len=strFile.GetLength();
int lastdir=0;
for (int i=len-1;i>=0;i--)
{
if (((int)strFile.GetAt(i))!=-1)
{
lastdir=i;//反射查找
break;
}
}
tmp=strFile.Right(4);
int pos=tmp.Find(_T(".txt"));//找后缀名
if (pos==-1)
{
strFile+=_T(".txt");
}
CStdioFile RecFile;
CFileException fileException;
if (RecFile.Open(strFile,CFile::typeText|CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive),&fileException)
{
m_HandleProgress.SetPos(0);
char* old_locale = _strdup( setlocale(LC_CTYPE,NULL) );
setlocale( LC_CTYPE, "chs" );//设定中文
RecFile.WriteString(_T(" 序号\t AA \t BB \t\t CC\t\t DD\t EE \t FF\t GG\r\n"));
RecFile.WriteString(_T("=========================================================================================================\r\n"));
for (int i=0;i{
RecFile.WriteString(m_ListCtrl.GetItemText(i,0));
RecFile.WriteString(_T("\t"));
RecFile.WriteString(m_ListCtrl.GetItemText(i,1));
RecFile.WriteString(_T("\t "));
RecFile.WriteString(m_ListCtrl.GetItemText(i,2));
RecFile.WriteString(_T(" \t"));
RecFile.WriteString(m_ListCtrl.GetItemText(i,3));
RecFile.WriteString(_T("\t"));
RecFile.WriteString(m_ListCtrl.GetItemText(i,4));
RecFile.WriteString(_T("\t "));
RecFile.WriteString(m_ListCtrl.GetItemText(i,5));
RecFile.WriteString(_T("\t"));
RecFile.WriteString(m_ListCtrl.GetItemText(i,6));
RecFile.WriteString(_T("\t"));
RecFile.WriteString(m_ListCtrl.GetItemText(i,7));
RecFile.WriteString(_T("\r\n"));
}
setlocale( LC_CTYPE, old_locale );
free( old_locale );//还原区域设定
RecFile.Close();
}
}
把列表控件里面的内容读出组合成一个字符串,然后把字符串写进文件即可.
void fnOutPutToFile(CListCtrl *pList)
{
CString sFile="d:\\文件名.txt";
CString sContent="";//文件内容存储
int iRowCount= pList->GetItemCount();
int iCellCount=pList->GetHeaderCtrl()->GetItemCount(); //取得列数
for(int iRow=0;iRow
////遍历列
CString sLine ;//行文本
for(int iCell=0;iCell
sLine+=pList->GetItemText(iRow,iCell);
sLine+= "\t" ;//行分隔定义,这里是制表符
}
//行结束,存储到总文本中
sContent+=sLine;
sContent+="\r\n";
}
}
运行的时候将对象地址放入即可
::fnOutPutToFile(&mcList);//mcList是CListCtrl控件对象名.