MFC 创建HTML格式数据并显示

来源:互联网 发布:琵琶行 知乎 编辑:程序博客网 时间:2024/05/17 00:59

typedef vector<CStringW> FileLines;
typedef vector<CStringW> HeadNameHtml;
typedef vector<CStringW> RowValue;
typedef map<int, RowValue> TableValueHtml;

//输出数据到临时文件,返回文件全名

CStringW OutputHtmlW(FileLines lineInfo, CStringW wcsFileName)
{
    FileLines::iterator ite;
    wchar_t wcsPath[MAX_PATH];
    wchar_t wcsLogFileName[MAX_PATH];
    memset(wcsPath, 0, sizeof(wcsPath));
    memset(wcsLogFileName, 0, sizeof(wcsLogFileName));

    GetModuleFileNameW(NULL, wcsPath, sizeof(wcsPath));//取得exe全名称
    wchar_t* pwcsEnd = wcsrchr(wcsPath,'//');

    pwcsEnd++;
    *pwcsEnd = '/0';

    wcscat(wcsPath, wcsFileName);
    std::wofstream output(wcsPath, ios::trunc);
    output.imbue(locale("chs") ); //设定当前编码为中文
    for (ite = lineInfo.begin(); ite != lineInfo.end(); ite++)
    {  
        output <<  (const wchar_t*)(*ite);
        output << endl;
    }
   
    output.close();
    return CStringW(wcsPath);

}


//将要显示的内容转换为html格式的数据

FileLines CreateHtmlContext(HeadNameHtml headNames, TableValueHtml items)
{
    CStringW wcsInfo(L"");
    CStringW wcsFileName((L"Report.html"));
    CStringW wcsFullName;
    TableValueHtml::iterator ite;
    FileLines lines;
    int iloop = 0;
    int iItemsCount = items.size();
    int iColumnCount = headNames.size();
    lines.insert(lines.end(), L"<html>");
    lines.insert(lines.end(), L" <title></title>");
    lines.insert(lines.end(), L"  <head> ");
    lines.insert(lines.end(), L"  <table border = 1> ");
    lines.insert(lines.end(), L"   <tr> ");
    for (; iloop < iColumnCount; iloop++) {

        lines.insert(lines.end(), L"   <th> ");
        lines.insert(lines.end(), headNames[iloop]);
        lines.insert(lines.end(), L" ");
        lines.insert(lines.end(), L"   <th> ");

    }
    lines.insert(lines.end(), L"   <tr> ");


    for(ite = items.begin(); ite != items.end(); ite++) {
        lines.insert(lines.end(), L"   <tr> ");
        for (iloop = 0; iloop < iColumnCount; iloop++) {
            lines.insert(lines.end(), L"   <td> ");
            CStringW value = (*ite).second[iloop];

            lines.insert(lines.end(), value);
            lines.insert(lines.end(), L" ");
            lines.insert(lines.end(), L"   <td> ");

        }
        lines.insert(lines.end(), L"   <tr> ");

    }
    lines.insert(lines.end(), L"   </table> ");
    lines.insert(lines.end(), L"  </head>");
    lines.insert(lines.end(),  L"</html>");


    return lines;
}

 

/*应用上面的两个函数将指定的内容在html中以表格的方式显示

void ShowHtmlFile()

{

 CStringW wcsFullName;
    CStringW wcsFileName(L"Report.html");//创建的文件名称
    TableValueHtml items; //要显示的内容
    HeadNameHtml headNames ;//表标题

.


.    ~添加内容到items, headNames~

.

.

 

    FileLines lines = CreateHtmlContext(headNames, items);//将要显示的内容转换为html格式的数据



    wcsFullName = OutputHtmlW(lines, wcsFileName); //输出数据到临时文件,返回文件全名
    ShellExecute(NULL, L"Open", L"IEXPLORE.EXE", wcsFullName, NULL, SW_SHOWNORMAL);//用浏览器显示文件

}