Qt导出文件到word(使用QAxObject)

话不多说直接上代码

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include 
#include 
#include 
#include 
#include 
#include 

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    bool open();
    void setType(bool isLandscape = true);
    int curPageWidth();
    void setFontSize(int size);
    void setAlignment(int index);
    void insertText(QString text);
    void insertPicture(QString filepath);
    void insertEnter();
    void insertTable(int row, int column);
    void setColumnWidth(int column,int width);
    void setCellText(int row,int column,const QString text);
    QVariant getCellText(int row,int column);
    void insertCellPicture(int row,int column,QString filepath);
    void MergeCell(int nStartRow, int nStartCol, int nEndRow, int nEndCol);
    void addTableRow(int nRow,int rowCount );
    void moveToEnd();
    void setOptionCheckSpell(bool flag);
    void save();
    void saveAs(QString newFileName);
    void close();
    void skipPage();
    void setTitle(QString title);
private:
    Ui::MainWindow *ui;
    QString s_error;
    QAxObject *m_pWord;      /* 指向整个Word应用程序 */
    QAxObject *m_pWorkDocuments;  /* 指向文档集,Word有很多文档 */
    QAxObject *m_pWorkDocument;   /* 指向m_sFile对应的文档,就是要操作的文档 */
};

#endif // MAINWINDOW_H

mainwindow.c

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString path = "C:/Users/45906/Desktop/1.doc";
    if(!open()){
        qDebug() << s_error;
        qDebug() << "open word fail!!!";
    }else{
        setType(true);
        setAlignment(0);
        insertText("hello world1");
        insertEnter();
        setAlignment(3);
        insertText("hello world2");
        insertEnter();
        setAlignment(2);
        insertText("hello world3");
        insertEnter();
        saveAs(path);
        close();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
/* 打开word */
bool MainWindow::open()
{
    m_pWord = new QAxObject;
    if(!m_pWord->setControl("Word.Application")){
        s_error += "错误:获取word组件失败,请确定是否安装了word!\n";
        return false;
    }
    m_pWord->setProperty("Visible", false);
    m_pWord->setProperty("DisplayAlerts", false); /* 关闭警告提示 */
    m_pWorkDocuments = m_pWord->querySubObject("Documents");
    if(!m_pWorkDocuments){
        s_error += "错误:获取文档失败\n";
        return false;
    }
    m_pWorkDocuments->dynamicCall("Add (void)");
    /* 获取当前激活的文档 */
    m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");
    return true;
}
/* 设置排版方式 */
void MainWindow::setType(bool isLandscape)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        if(isLandscape){
            selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientLandscape");
        }else{
            selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientPortrait");
        }
    }else{
        QMessageBox::information(this,tr("警告"),tr("设置排版方式失败!"),QMessageBox::Close);
    }
}
/* 获取当前页宽 */
int MainWindow::curPageWidth()
{
    int width;
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        width = selection->querySubObject("PageSetup")->property("PageWidth").toInt();;
        return width;
    }else{
        QMessageBox::information(this,tr("警告"),tr("获取当前页宽失败!"),QMessageBox::Close);
    }
    return 0;
}
/* 设置字体大小 */
void MainWindow::setFontSize(int size)
{
   QAxObject* selection = m_pWord->querySubObject("Selection");
   if(selection){
       selection->querySubObject("Font")->setProperty("Size",size);
   }
}
/* 设置文字对齐方式 */
void MainWindow::setAlignment(int index)
{
    QAxObject *selection = m_pWord->querySubObject("Selection");
    if(selection){
        if(index == 0){
            selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphCenter");
        }else if(index == 1){
            selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphJustify");
        }else if(index == 2){
            selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphRight");
        }else if(index == 3){
            selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphLeft");
        }
    }else{
        QMessageBox::information(this,tr("警告"),tr("设置文字对齐失败!"),QMessageBox::Close);
    }
}
/* 插入文本 */
void MainWindow::insertText(QString text)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(selection){
        selection->dynamicCall("TypeText(const QString&)",text);
    }else{
        QMessageBox::information(this,tr("警告"),tr("插入文本%1失败!").arg(text),QMessageBox::Close);
    }
}
/* 插入图片 */
void MainWindow::insertPicture(QString filepath)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(selection){
        QString filename = filepath;
        filename.replace("/","\\");
        QAxObject *Inlineshapes = selection->querySubObject("InlineShapes");
        Inlineshapes->dynamicCall("AddPicture(const QString&)",filename);
        delete Inlineshapes;
    }else{
        QMessageBox::information(this,tr("警告"),tr("插入图片%1失败!").arg(filepath),QMessageBox::Close);
    }

}
/* 插入回车 */
void MainWindow::insertEnter()
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(selection){
        selection->dynamicCall("TypeParagraph(void)");
    }else{
        QMessageBox::information(this,tr("警告"),tr("插入回车失败!"),QMessageBox::Close);
    }
}
/* 插入表格 */
void MainWindow::insertTable(int row, int column)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject *range = selection->querySubObject("Range");
        QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
        QVariantList params;
        params.append(range->asVariant());
        params.append(row);
        params.append(column);
        tables->querySubObject("Add(QAxObject*, int, int, QVariant&, QVariant&)", params);
        QAxObject* table = selection->querySubObject("Tables(1)");
        table->setProperty("Style","网格型");
    }else{
        QMessageBox::information(this,tr("警告"),tr("插入表格失败!"),QMessageBox::Close);
    }
}
/* 设置单元格列宽 */
void MainWindow::setColumnWidth(int column, int width)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        table->querySubObject("Columns(int)",column)->setProperty("Width",width);
    }
}
/* 设置单元格内容 */
void MainWindow::setCellText(int row, int column, const QString text)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        table->querySubObject("Cell(int, int)",row,column)->querySubObject("Range")->dynamicCall("SetText(QString)", text);
    }else{
        QMessageBox::information(this,tr("警告"),tr("设置单元格内容失败!"),QMessageBox::Close);
    }
}
/* 获取单元格内容 */
QVariant MainWindow::getCellText(int row, int column)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        return table->querySubObject("Cell(int, int)",row,column)->querySubObject("Range")->property("Text");
    }else{
        QMessageBox::information(this,tr("警告"),tr("获取单元格内容失败!"),QMessageBox::Close);
    }
    return 0;
}
/* 表格插入图片 */
void MainWindow::insertCellPicture(int row, int column, QString filepath)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        QAxObject* range = table->querySubObject("Cell(int, int)",row,column)->querySubObject("Range");
        range->querySubObject("InlineShapes")->dynamicCall("AddPicture(const QString&)",filepath);
    }else{
        QMessageBox::information(this,tr("警告"),tr("表格插入图片失败!"),QMessageBox::Close);
    }
}
/* 合并单元格 */
void MainWindow::MergeCell(int nStartRow,int nStartCol,int nEndRow,int nEndCol)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        QAxObject* StartCell =table->querySubObject("Cell(int, int)",nStartRow,nStartCol);
        QAxObject* EndCell = table->querySubObject("Cell(int, int)",nEndRow,nEndCol);
        StartCell->querySubObject("Merge(QAxObject *)",EndCell->asVariant());
    }else{
        QMessageBox::information(this,tr("警告"),tr("合并单元格失败!"),QMessageBox::Close);
    }
}
/* 添加单元格内的行 */
void MainWindow::addTableRow(int nRow, int rowCount)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QAxObject* table = selection->querySubObject("Tables(1)");
        QAxObject* rows =table->querySubObject("Rows");
        int Count =rows->dynamicCall("Count").toInt();
        if(0< nRow && nRow < Count ){
            for(int i =0; i< rowCount; ++i){
                QString sPos = QString("Item(%1)").arg(nRow+i);
                QAxObject* row= rows->querySubObject(sPos.toStdString().c_str());
                QVariant param =row ->asVariant();
                rows->dynamicCall("Add(Variant)",param);
            }
        }
    }else{
        QMessageBox::information(this,tr("警告"),tr("合并单元格失败!"),QMessageBox::Close);
    }
}

/* 跳出单元格 */
void MainWindow::moveToEnd()
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(selection){
        QVariantList params;
        params.append(6);
        params.append(0);
        selection->dynamicCall("EndOf(QVariant&, QVariant&)", params).toInt();
    }
}
/* 设置拼写检查 */
void MainWindow::setOptionCheckSpell(bool flag)
{
    QAxObject* opetions = m_pWord->querySubObject("Options");
    if(opetions){
        opetions->setProperty("CheckGrammarAsYouType",flag);
        opetions->setProperty("CheckGrammarWithSpelling",flag);
        opetions->setProperty("ContextualSpeller",flag);
        opetions->setProperty("CheckSpellingAsYouType",flag);
    }
}
/* 保存 */
void MainWindow::save()
{
    if(m_pWorkDocument)
        m_pWorkDocument->dynamicCall("Save()");
}
/* 另存 */
void MainWindow::saveAs(QString newFileName)
{
    if(m_pWorkDocument)
        m_pWorkDocument->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(newFileName));
}
/* 关闭 */
void MainWindow::close()
{
    if(m_pWorkDocument)
        m_pWorkDocument->dynamicCall("Close (boolean)",false);
    if(m_pWord)
        m_pWord->dynamicCall("Quit (void)");
    if(m_pWorkDocuments)
        delete m_pWorkDocuments;
    if(m_pWord)
        delete m_pWord;
    m_pWorkDocument = nullptr;
    m_pWorkDocuments = nullptr;
    m_pWord = nullptr;
}
/* 换页 */
void MainWindow::skipPage()
{
    insertText("\x0c");
}

直接复制粘贴就能用,没有其他东西了

你可能感兴趣的:(Qt)