【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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

Qt实战之开发软件数据获取助手

前段时间,受朋友委托,需要做一个能够获取别人软件文本框中内容的助手。当然这需要调用win api来解决问题。一开始,我想都没想,就用getWindowText()。。。。居然没用,好郁闷。于是查msd...
  • WU5151
  • WU5151
  • 2015年07月28日 10:09
  • 1395

如何用应用程序模拟键盘和鼠标按键

在Windows大行其道的今天,windows界面程序受到广大用户的欢迎。对这些程序的操作不外乎两种,键盘输入控制和鼠标输入控制。有时,对于繁杂的,或重复性的输入操作,我们能否通过编制程序来代替手工输...
  • hhaoma
  • hhaoma
  • 2008年10月28日 23:52
  • 3834

矩阵类基本操作的简单实现

  • 2008年11月06日 15:29
  • 271KB
  • 下载

用java简单的实现单链表的基本操作

此代码仅供参考,如有疑问欢迎评论: [java] view plain copy package com.tyxh.link;   //节点类   public class N...

用java简单的实现单链表的基本操作

此代码仅供参考,如有疑问欢迎评论: package com.tyxh.link; //节点类 public class Node { protected Node next; //指针域 ...

C++实现循环列队的基本操作

  • 2011年03月29日 22:43
  • 1.97MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【C++简单写Word】(三) 基本操作的实现
举报原因:
原因补充:

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