【第22期】观点:IT 行业加班,到底有没有价值?

【C++简单写Word】(三) 基本操作的实现

原创 2016年08月29日 14:42:29

我实现了一些较为简单的功能:比如输出文本信息,将其格式化,输出表格数据,以及绘画柱状图的功能

ToWord.h

#pragma once
#include "CApplication.h"
#include "CDocument0.h"
#include "CDocuments.h"
#include "CSelection.h"
#include "CFont0.h"
#include "CParagraph.h"
#include "CParagraphs.h"
#include "CTable0.h"
#include "CTables0.h"
#include "CRange.h"
#include "CCell.h"
#include "CCells.h"
#include "CnlineShape.h"
#include "CnlineShapes.h"
#include "COLEFormat.h"
#include "ToExcel.h"

class CToWord
{
public:
    // 无参数构造函数,文件生成在Debug文件夹下Demo.docx
    CToWord();
    // 有参数构造函数,传入完整的生成地址
    CToWord(CString);
    ~CToWord();
private:
    // Word部分
    CApplication Application;
    CDocuments Documents;
    CDocument0 Document;
    CSelection Selection;
    CFont0 Font;
    CParagraphs Paragraphs;
    CParagraph Paragraph;
    CTables0 Tables;
    CTable0 Table;
    CRange Range;
    CCells Cells;
    CCell Cell;
    CnlineShape Shape;
    CnlineShapes Shapes;
    COLEFormat OLEFormat;

    CToExcel *ToExcel;

public:
    // 初始化
    void Create(void);

private:
    BOOL m_bIsVisible;

public:
    // 输出文本
    void OutText(CString);
    // 换行
    void NewLine(void);
    // 开辟新的一行并将光标置于新行的最前面
    void MoveNewLine(void);
    // 向右移动光标
    void MoveRight(void);
    //  移到到表格 头 尾
    void MoveHome(void);
    void MoveEnd(void);
    void EndOf(void);
    // 向下移动
    void MoveDown(void);
//  void MoveLeft(void);
public:
    // 生成表格 row行,columns列
    void OutTables(int row, int columns);
public:
    // 样式:0为正文,1.2.3分别为标题1.2.3
    void PutStyle(int);
    // 0为居左,1为居中,2为居右
    void PutAlignment(long);
public:
    // 字体大小
    void PutFontSize(float);
    // 下划线:从右数第i个字符到第i+n个字符下加下划线
    void PutUnderLine(int i, int n);
public:
    // 生成图表 柱状图 = 51. 饼图 = 5
    CToExcel* OutShapes(int);
private:
    CString SavePoistion;
public:
    // 另存为
    void SaveAs(void);
    // 得到当前根目录
    CString GetModuleDir(void);
};

ToWord.cpp

#include "stdafx.h"
#include "ToWord.h"
#include <windows.h>

CToWord::CToWord()
{
    SavePoistion = GetModuleDir();
    SavePoistion += L"\\Demo.doc";
}

CToWord::CToWord(CString poistion)
{
    SavePoistion = poistion;
}


CToWord::~CToWord()
{
    Application.put_ScreenUpdating(true);
    delete(ToExcel);
    Application.Quit(COleVariant((short)0),
        COleVariant((short)0),
        COleVariant((short)0));
    SaveAs();
    Application.ReleaseDispatch();
    Documents.ReleaseDispatch();
    Document.ReleaseDispatch();
    Selection.ReleaseDispatch();
    Font.ReleaseDispatch();
    Paragraphs.ReleaseDispatch();
    Paragraph.ReleaseDispatch();
    Tables.ReleaseDispatch();
    Table.ReleaseDispatch();
    Range.ReleaseDispatch();
    Cells.ReleaseDispatch();
    Cell.ReleaseDispatch();
    Shape.ReleaseDispatch();
    Shapes.ReleaseDispatch();
    OLEFormat.ReleaseDispatch();
}

void CToWord::Create(void)
{
    if (!AfxOleInit())
    {
        AfxMessageBox(_T("初始化OLE出错"));
        return;
    }
    if (!Application.CreateDispatch(_T("Word.Application")))//启动WORD  
    {
        AfxMessageBox(_T("无法找到Office?"));
        return;
    }
    // Documents
    Documents = Application.get_Documents();
    if (!Documents.m_lpDispatch)
    {
        AfxMessageBox(_T("Documents创建失败!"), MB_OK | MB_ICONWARNING);
        return;
    }
    CComVariant Template(_T(""));
    CComVariant NewTemplate(false), DocumentType(0), Visible;
    Documents.Add(&Template, &NewTemplate, &DocumentType, &Visible);

    // Document
    Document = Application.get_ActiveDocument();
    if (!Document.m_lpDispatch)
    {
        AfxMessageBox(_T("Document获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    // Selection
    Selection = Application.get_Selection();
    if (!Selection.m_lpDispatch)
    {
        AfxMessageBox(_T("Select获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    // Paragraphs
    Paragraphs = Selection.get_ParagraphFormat();
    if (!Paragraphs.m_lpDispatch)
    {
        AfxMessageBox(_T("Paragraphs获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    // Font
    Font = Selection.get_Font();
    if (!Font.m_lpDispatch)
    {

        AfxMessageBox(_T("Font获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    // Tables
    Tables = Document.get_Tables();
    if (!Tables.m_lpDispatch)
    {
        AfxMessageBox(_T("Tables获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    // Range
    Range = Selection.get_Range();
    if (!Range.m_lpDispatch)
    {
        AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }

    Shapes = Selection.get_InlineShapes();
    if (!Shapes.m_lpDispatch)
    {
        AfxMessageBox(_T("Shapes获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }
    Application.put_Visible(true);
}

void CToWord::OutText(CString text)
{
    Selection.TypeText(text);
}

void CToWord::NewLine(void)
{
    Selection.TypeParagraph();
}

void CToWord::MoveNewLine(void)
{
    Selection.MoveRight(COleVariant((short)12), COleVariant((short)1), COleVariant((short)0));
}

void CToWord::MoveRight(void)
{
    Selection.MoveRight(COleVariant((short)1), COleVariant((short)1), COleVariant((short)0));
}

void CToWord::MoveHome(void)
{
    Selection.HomeKey(COleVariant((short)10), COleVariant((short)0));
}

void CToWord::MoveEnd(void)
{
    Selection.EndKey(COleVariant((short)5), COleVariant((short)0));
}

void CToWord::EndOf(void)
{
    Selection.EndOf(COleVariant((short)5), COleVariant((short)0));
}

void CToWord::MoveDown(void)
{
    Selection.MoveDown(COleVariant((short)7), COleVariant((short)1), COleVariant((short)0));
}

void CToWord::OutTables(int row, int columns)
{
    Range.SetRange(Selection.get_End(), Selection.get_End());
    Tables.Add(Range, row, columns, COleVariant((short)1), COleVariant((short)0));
}

void CToWord::PutStyle(int istyle)
{
    CString style;
    switch (istyle)
    {
    case 0:
        style = L"正文"; break;
    case 1:
        style = L"标题 1"; break;
    case 2:
        style = L"标题 2"; break;
    case 3:
        style = L"标题 3"; break;
    default:
        style = L"正文"; break;
    }
    CComVariant Cstyle(style);
    Selection.put_Style(&Cstyle);
}

void CToWord::PutAlignment(long index)
{
    Paragraphs.put_Alignment(index);
}

void CToWord::PutFontSize(float size)
{
    Font.put_Size(size);
}

void CToWord::PutUnderLine(int i, int n)
{
    Selection.MoveLeft(COleVariant((long)1), COleVariant((long)i), COleVariant((long)0));
    Selection.MoveLeft(COleVariant((long)1), COleVariant((long)n), COleVariant((long)1));
    Font.put_UnderlineColor(1);
    Font.put_Underline(1);
}

CToExcel* CToWord::OutShapes(int Choice)
{
    COleVariant VarOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  // 默认值
    Range.SetRange(Selection.get_End(), Selection.get_End()+1000);
    CComVariant r(Range);
    Shape = Shapes.AddOLEObject(COleVariant(L"Excel.Chart"), VarOpt, VarOpt, VarOpt, VarOpt, VarOpt, VarOpt, &r);
    OLEFormat = Shape.get_OLEFormat();
    LPDISPATCH object;
    CWorkbook workbook = OLEFormat.get_Object();
    CWorkbook *pbook = &workbook;
    ToExcel = new CToExcel(pbook);
    ToExcel->PutClassType(Choice);
    return ToExcel;
}

void CToWord::SaveAs(void)
{
//  SavePoistion =  "D:\\demo.doc";
    Document.SaveAs(COleVariant(SavePoistion), //FileName
        COleVariant((short)1), //FileFormat
        COleVariant((short)FALSE), //LockComments
        COleVariant(_T("")), //Password;
        COleVariant((short)FALSE), //AddToRecentFiles
        COleVariant(_T("")), //WritePassword
        COleVariant((short)FALSE), //ReadOnlyRecommended 
        COleVariant((short)FALSE), //EmbedTrueTypeFonts 
        COleVariant((short)FALSE), //SaveNativePictureFormat 
        COleVariant((short)FALSE), //SaveFormsData 
        COleVariant((short)FALSE), //SaveAsAOCELetter
        COleVariant((short)0), //Encoding 
        COleVariant((short)FALSE), //InsertLineBreaks
        COleVariant((short)FALSE), //AllowSubstutitions,
        COleVariant((short)0), //LineEnding
        COleVariant((short)0) //AddBiDiMarks
    );
}

CString CToWord::GetModuleDir(void)
{
    HMODULE module = GetModuleHandle(0);
    WCHAR pFileName[MAX_PATH];
    GetModuleFileName(module, pFileName, MAX_PATH);

    CString csFullPath(pFileName);
    int nPos = csFullPath.ReverseFind(_T('\\'));
    if (nPos < 0)
        return CString("");
    else
        return csFullPath.Left(nPos);
}

如果需要在Word中添加图表,则需要导入支持Excel的头文件
ToExcelChart.h

#pragma once
// Excel头文件
#include "CChartObjects.h"
#include "CCharts.h"
#include "CWorkbook.h"
#include "CWorksheets.h"
#include "CWorksheet.h"
#include "CRange0.h"
#include "CChartTitle.h"
#include "CChart.h"
#include "CAxisTitle.h"
#include "CAxis.h"
#include "CChartArea.h"

#include <vector>
using namespace std;
class CToExcel
{
private:
    // Excel部分
    CChartObjects ChartObjects;
    CCharts Charts;
    CWorkbook Workbook;
    CWorksheets Worksheets;
    CWorksheet Worksheet;
    CRange0 Range;
    CChartTitle ChartTitle;
    CChart Chart;
    CAxisTitle AxisTitle;
    CAxis Axis;
    CChartArea ChartArea;
public:
    CToExcel();
    CToExcel(CWorkbook*&);
    ~CToExcel();
private:
    // 列数
    int m_iColNumber;
public:
    // 设置图表类型 1 = 柱状图 , 2 = 折线图, 3 = 饼状图
    void PutClassType(int);
    // 设置图表标题
    void PutTitle(CString Title = L"Title");
    // 设置纵坐标标题
    void PutVerticalTitle(CString Title = L"Vertical coordinate title");
    // 行坐标轴
    void PutHorizontalData(vector<CString>);
    // 列坐标轴
    void PutVerticalData(vector<CString>);
    // 数据
    void PutData(vector<double>);
private:
    // 将第row行第col列 转换为 A1 B1 这样的形式
    CString Transform(int row = 1, int col = 1);
};

ToExcelChart.cpp

#include "stdafx.h"
#include "ToExcel.h"


CToExcel::CToExcel()
{
}

CToExcel::CToExcel(CWorkbook*& Workbook)
{
    this->Workbook = *Workbook;
    Worksheets = this->Workbook.get_Sheets();
    if (!Worksheets.m_lpDispatch)
    {
        AfxMessageBox(_T("Worksheets获取失败!"), MB_OK | MB_ICONWARNING);
        return;
    }
    Worksheet = Worksheets.get_Item(COleVariant((long)2)); 
    // 清空原有的数据
    Range = Worksheet.get_Range(COleVariant(_T("A1")), COleVariant(_T("D7")));
    Range.Clear();

    Charts = this->Workbook.get_Charts();
    Chart = Charts.get_Item(COleVariant((long)1));
    m_iColNumber = 0;
}


CToExcel::~CToExcel()
{

    ChartObjects.ReleaseDispatch();
    Charts.ReleaseDispatch();
    Range.ReleaseDispatch();
    ChartTitle.ReleaseDispatch();
    Chart.ReleaseDispatch();
    AxisTitle.ReleaseDispatch();
    Axis.ReleaseDispatch();
    ChartArea.ReleaseDispatch();
    Workbook.ReleaseDispatch();
    Worksheets.ReleaseDispatch();
    Worksheet.ReleaseDispatch();
    delete Workbook;
}

void CToExcel::PutClassType(int choice)
{
    switch (choice)
    {
    case 2:
        Chart.put_ChartType(4); break;
    case 3:
        Chart.put_ChartType(5); break;
    default:
        break;
    }
}

void CToExcel::PutTitle(CString Title)
{
    Chart.put_HasTitle(TRUE);
    ChartTitle = Chart.get_ChartTitle();
    ChartTitle.put_Text(Title);
}

void CToExcel::PutVerticalTitle(CString Title)
{
    Chart.SetElement(310);
    Axis = Chart.Axes(COleVariant((long)2), 1);
    AxisTitle = Axis.get_AxisTitle();
    AxisTitle.put_Text(Title);
}

void CToExcel::PutHorizontalData(vector<CString> Datavector)
{

    COleVariant VarOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    m_iColNumber = Datavector.size();
    Range = this->Worksheet.get_Range(COleVariant(_T("A1")), COleVariant(_T("D7")));
    for (int index = 0; index < Datavector.size(); index++)
    {
        Range = Worksheet.get_Range(COleVariant(Transform(1,index+2)), VarOpt);
        Range.put_Value2(COleVariant(Datavector[index]));
    }
}

void CToExcel::PutVerticalData(vector<CString> Datavector)
{
    COleVariant VarOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    for (int index = 0; index < Datavector.size(); index++)
    {
        Range = Worksheet.get_Range(COleVariant(Transform(index+2, 1)), VarOpt);
        Range.put_Value2(COleVariant(Datavector[index]));
    }
}

void CToExcel::PutData(vector<double> Datavector)
{
    COleVariant VarOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    int num = 0;
    for (int index1 = 0; ; index1++)
    {
        for (int index2 = 0;; index2++)
        {
            Range = Worksheet.get_Range(COleVariant(Transform(index1+2, index2+2)), VarOpt);
            Range.put_Value2(COleVariant(Datavector[num]));

            num++;

            if ((num) % m_iColNumber == 0)
            {
                break;
            }
        }
        if (num >= Datavector.size())
        {
            break;
        }
    }
}

CString CToExcel::Transform(int row, int col)
{
    CString result;
    switch (col)
    {
    case 1:result = "A"; break;
    case 2:result = "B"; break;
    case 3:result = "C"; break;
    case 4:result = "D"; break;
    case 5:result = "E"; break;
    case 6:result = "F"; break;
    case 7:result = "G"; break;
    case 8:result = "H"; break;
    case 9:result = "I"; break;
    case 10:result = "J"; break;
    case 11:result = "K"; break;
    case 12:result = "L"; break;
    case 13:result = "M"; break;
    case 14:result = "N"; break;
    case 15:result = "O"; break;
    case 16:result = "P"; break;
    case 17:result = "Q"; break;
    case 18:result = "R"; break;
    case 19:result = "S"; break;
    case 20:result = "T"; break;
    case 21:result = "result"; break;
    case 22:result = "V"; break;
    case 23:result = "W"; break;
    case 24:result = "X"; break;
    case 25:result = "Y"; break;
    case 26:result = "Z"; break;
    defaresultlt:break;
    }
    CString cs;
    cs.Format(_T("%d"), row);
    result = result + cs;
    return result;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

【C++简单写Word】(四) 整理及反思

在学习用代码操作Word的时候真是遇到了许许多多的困难啊,不过好歹一一克服了。 我要将我这段时间的所学整理成笔记。 在如何初始化Word或者Excel上,网络上有很多详细的教程我就不在啰嗦了。不过...

【C++简单写Word】(一)概念了解

这些都是我在学习的时候看到的一些基础概念。均来源于百度百科 Component Object Model(COM——组件对象模型) 组件对象模型,一种面向对象的编程模式。它定义了对象在单个应用程序...

摘录的一些Bjarne Stroustrup关于C++的谈话内容

1 专访 Bjarne Stroustrup2 C++ 热点问题一席谈3 C++0x 热点问题访谈4 C++0x 概览 专访 Bjarne Stroust...

C++ 中数据类型互转

转自:http://hi.baidu.com/keenmeng_study/blog/item/427505245b40236c35a80f6f.html 传参数时不可以传CString ,CString 在ATL MFC中定义是不同的,而且在各个版本里也略有不同。注意。 有两方法LPCTSTR和GetBuffer() 看看这个 LPCTSTR 与 GetBuf
  • jgsj
  • jgsj
  • 2010-12-22 10:41
  • 145

各种排序算法及其实现总结

排序算法总结 1.插入排序 一般来说,插入排序 都采用in-place在数组上实现。具体算法描述如下: 从第一个元素开始,该元素可以认为已经被排序 取出下一个元素,在已经排序的元素序列中从后向前扫描 如果该元素(已排序)大于新元素,将该元素移到下一位置 重复步骤3,直到找到已排序的元素小于或者等于新元素的位

C++智能指针梳理

参考: https://en.wikipedia.org/wiki/Memory_leak (维基百科,内存泄漏)https://en.wikipedia.org/wiki/Resource_lea...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)