【MFC编程】MFC将ListCtrl列表导出到Excel-采用文件流写Excel兼容Html格式(不需要Excel环境)

 

如标题所言,将ListCtrl的内容导出到Excel文件。不需要Excel环境支持!

 

	TCHAR szFilter[] = _T("Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*||");   
	CFileDialog file(FALSE, _T(".xls"), _T("TransForm"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this);  

	CString strSavePath = _T(""); //!<保存路径  
	if(IDOK == file.DoModal())  
	{  
		strSavePath = file.GetPathName();  
	}

	//!<导出的xls文件路径
	if (strSavePath != _T(""))
	{
		std::string szTitle = "TransForm";
		std::string szHander = "";
		szHander = "
"; //!GetItemCount(); ///列数 std::fstream file; file.open(strSavePath, std::ios_base::out); file.write(szHander.c_str(), szHander.length()); //!<写入标题行 std::string szFiled = ""; file.write(szFiled.c_str(), szFiled.length()); file.write(szTR.c_str(), szTR.length()); //!<根据列头写单元格 char szText[MAX_PATH] = {0}; LVCOLUMN LvColumn; LvColumn.mask = LVCF_TEXT; LvColumn.pszText = szText; //!<标题名称 LvColumn.cchTextMax = MAX_PATH; for (int i = 0; i < nCloumn; ++i) { if(m_lstResult.GetColumnWidth(i) <= 0) continue; //!<如果列宽为0则视为隐藏 m_lstResult.GetColumn(i, &LvColumn); szFiled = ""; file.write(szFiled.c_str(), szFiled.length()); } file.write(szEndTR.c_str(), szEndTR.length()); CString strValue = _T(""); int nItemsCount = m_lstResult.GetItemCount(); //!<获取列表总行数 if (nItemsCount > 0) { for(int i = 0; i < nItemsCount; ++i) //!<一行一行的写,遍历行在外层循环 { file.write(szTR.c_str(), szTR.length()); for (int j = 0; j < nCloumn; ++j) { if(m_lstResult.GetColumnWidth(j) <= 0) continue; strValue = m_lstResult.GetItemText(i, j); szFiled = ""; file.write(szFiled.c_str(), szFiled.length()); } file.write(szEndTR.c_str(), szEndTR.length()); } file.write(szEndTR.c_str(), szEndTR.length()); } file.close(); ShellExecute(NULL, _T("open"), strSavePath, NULL, NULL, SW_SHOW); }

 

 

 

 

 

std::string MakeSafeHTMLText(const std::string& v_szContent)
{
	std::string szResult = "";
	for (int i = 0; i < v_szContent.length(); ++i)
	{
		char ch = v_szContent[i];
		switch(ch)
		{
		case '<':
			szResult += "<";
		case '>':
			szResult += ">";
		case '&':
			szResult += "&";
		case '"':
			szResult += """;
		case '\'':
			szResult += "'";
			break;
		default:
			szResult += ch;
			break;
		}
	}

	return szResult;
}

 

 

 

你可能感兴趣的:(MFC界面开发)

" + CFunLib::MakeSafeHTMLText(szTitle) + "
" + CFunLib::MakeSafeHTMLText(LvColumn.pszText) + "" + CFunLib::MakeSafeHTMLText(strValue.operator LPCTSTR()) + "