使用单文档视图结构把Word嵌入到VC程序中(2)

本文介绍如何在VC++项目中嵌入Word文档,并实现对Word文档的操作,如打开、编辑及保存等功能。通过引入MSWORD.OLB,可以方便地使用Word::_DocumentPtr类来操作Word文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境;win7 64,vs2008 sp1,word2013

一.新建一单文档,复合文档选择容器,同时选中活动文档容器和支持复合文件




二.参考http://blog.youkuaiyun.com/dragoo1/article/details/41704245,使单文档打开的时候可以打开一个现有word。关键代码
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void CTest1203View::OnInitialUpdate()  
  2. {  
  3.     CView::OnInitialUpdate();  
  4.   
  5.     // TODO: 写入最终选择模式代码之后移除此代码  
  6.     m_pSelection = NULL;    // 初始化选定内容  
  7.   
  8.     EmbedAutomateWord("D:\\test.docx", 0);   
  9.   
  10. }  
  11.   
  12. void CTest1203View::EmbedAutomateWord(CString sDocPath, int isNewDocDocment)  
  13. {  
  14.     //Change the cursor so that theuser knows that something exciting is going  
  15.     //on.  
  16.     BeginWaitCursor();  
  17.     CTest1203CntrItem*pItem = NULL;  
  18.     TRY{  
  19.         //Get thedocument that is associated with this view, and be sure that itis  
  20.         //valid.  
  21.         CTest1203Doc* pDoc =GetDocument();  
  22.         ASSERT_VALID(pDoc);  
  23.         //Create a newitem associated with this document, and be sure that it is  
  24.         //valid.  
  25.         pItem = new CTest1203CntrItem(pDoc);  
  26.         ASSERT_VALID(pItem);  
  27.         // Get the ClassID for the Word document.  
  28.         // This is usedin creation.  
  29.         CLSID clsid;  
  30.         if(FAILED(::CLSIDFromProgID(L"Word.document",&clsid)))  
  31.             //Anyexception will do. You just need to break out of the  
  32.             //TRYstatement.  
  33.             AfxThrowMemoryException();  
  34.         if(isNewDocDocment==0) //如果是打开文档  
  35.         {  
  36.             if(!pItem->CreateFromFile(sDocPath, clsid))  
  37.                 AfxThrowMemoryException();  
  38.         }  
  39.         else  
  40.         {  
  41.             // Create theWord embedded item.  
  42.             if(!pItem->CreateNewItem(clsid))  
  43.                 //Anyexception will do. You just need to break out of the  
  44.                 //TRYstatement.  
  45.                 AfxThrowMemoryException();  
  46.         }  
  47.         //Make sure thatthe new CContainerItem is valid.  
  48.         ASSERT_VALID(pItem);  
  49.         // Start theserver to edit the item.  
  50.         pItem->DoVerb(OLEIVERB_SHOW,this);  
  51.         // As anarbitrary user interface design, this sets the  
  52.         // selection tothe last item inserted.  
  53.         m_pSelection =pItem;   // Setselection to the last inserted item.  
  54.         pDoc->UpdateAllViews(NULL);  
  55.         //Query for thedispatch pointer for the embedded object. In  
  56.         //this case, thisis the Word document.  
  57.         //LPDISPATCH lpDisp;  
  58.         //lpDisp = pItem->GetIDispatch();  
  59.         //Add text to theembedded Word document.  
  60.         //  CDocumentwdDoc;  
  61.         //  CRangewdRange;  
  62.         //set CDocument0wdDoc to use lpDisp, the IDispatch* of the  
  63.         //actualdocument.  
  64.         //  wdDoc.AttachDispatch(lpDisp);  
  65.         //Get a CRangeobject for the document.  
  66.         //wdRange =wdDoc.Range(COleVariant( (long)DISP_E_PARAMNOTFOUND, VT_ERROR),  
  67.         //       COleVariant( (long)DISP_E_PARAMNOTFOUND, VT_ERROR ) );  
  68.         //Fill the rangewith the string "Hello, World!"  
  69.         //wdRange.put_Text("Hello, World!" );  
  70.         //wdRang.  
  71.     }  
  72.     //Clean up if something went wrong.  
  73.     CATCH(CException, e){  
  74.         if(pItem !=NULL){  
  75.             ASSERT_VALID(pItem);  
  76.             pItem->Delete();  
  77.         }  
  78.         AfxMessageBox(IDP_FAILED_TO_CREATE);  
  79.     }  
  80.     END_CATCH  
  81.     //Set the cursor back to normal so theuser knows exciting stuff  
  82.     //is no longer happening.  
  83.     EndWaitCursor();  
  84.   
  85. }  

三.添加对MSWORD.OLB的引用
1.在stdafx.h添加如下代码
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //copy from C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE15\MSO.DLL(win7_x64 computer)  
  2. #import "lib\win7_x86\MSO.DLL" rename("RGB", "_RGB1") rename("DocumentProperties", "_DocumentProperties1")  
  3. //copy from C:\Program Files (x86)\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB(win7_x64 computer)  
  4. #import "lib\win7_x86\VBE6EXT.OLB"  
  5. //copy from word2013  
  6. #import "lib\word\word2013\MSWORD.OLB" rename("ExitWindows", "_ExitWindows1"),rename("FindText", "_FindText1")  
2.在CTest1203View.h添加2个public变量
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public:  
  2.     Word::_ApplicationPtr g_lpApp;  
  3.     Word::_DocumentPtr m_lpWord;  

四.添加一个菜单,并添加相应事件
1.CTest1203View.h:
    afx_msg void OnTest();

2.CTest1203View.cpp:
......
ON_COMMAND(ID_TEST, &CTest1203View::OnTest)
......

3.CTest1203View.cpp:
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void CTest1203View::OnTest()  
  2. {  
  3.     // TODO: 在此添加命令处理程序代码  
  4.     m_lpWord = m_pSelection->GetIDispatch();  
  5.     g_lpApp = m_lpWord->GetApplication();  
  6.     Word::SelectionPtr sel = g_lpApp->GetSelection();  
  7.     sel->PutText("这是测试");  
  8.   
  9.     CString strPathName("D:\\test1.docx");  
  10.     int filetype = 0;  
  11.     CString sFileExt = "docx";  
  12.     if(sFileExt=="docx")  
  13.         filetype = 12;  
  14.     CComVariant FileName(strPathName);  
  15.     CComVariant FileFormat(filetype);       
  16.     CComVariant LockComments(false),Password(_T(""));  
  17.     CComVariant AddToRecentFiles(true),WritePassword(_T(""));  
  18.     CComVariant ReadOnlyRecommended(false),EmbedTrueTypeFonts(false);  
  19.     CComVariant SaveNativePictureFormat(false),SaveFormsData(false);  
  20.     CComVariant SaveAsAOCELetter(false);  
  21.     CComVariant Encoding(true);   
  22.     CComVariant InsertLineBreaks(false);  
  23.     CComVariant AllowSubstitutions(true);  
  24.     CComVariant LineEnding(false);  
  25.     CComVariant AddBiDiMarks(false);  
  26.     CComVariant CompatibilityMode(14);  
  27.   
  28.     if(sFileExt=="docx")  
  29.     {  
  30.         CComVariant Encoding(false);  
  31.         m_lpWord->SaveAs2(&FileName,&FileFormat,&LockComments,&Password,  
  32.             &AddToRecentFiles,&WritePassword,&ReadOnlyRecommended,  
  33.             &EmbedTrueTypeFonts,&SaveNativePictureFormat,&SaveFormsData,  
  34.             &SaveAsAOCELetter, &Encoding, &InsertLineBreaks, &AllowSubstitutions, &LineEnding, &AddBiDiMarks, &CompatibilityMode);  
  35.     }  
  36.     else  
  37.     {  
  38.         m_lpWord->SaveAs(&FileName,&FileFormat,&LockComments,&Password,  
  39.             &AddToRecentFiles,&WritePassword,&ReadOnlyRecommended,  
  40.             &EmbedTrueTypeFonts,&SaveNativePictureFormat,&SaveFormsData,  
  41.             &SaveAsAOCELetter);  
  42.     }  
  43. }  

4.CTest1203View.cpp:
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. CTest1203View::~CTest1203View()  
  2. {  
  3.     //释放容器  
  4.     if(m_pSelection!=NULL)  
  5.     {  
  6.         //m_pSelection->Release();  
  7.         m_pSelection->Delete();//该方法包含Release(),并有其他处理  
  8.         m_pSelection = NULL;  
  9.     }  
  10.     //释放word  
  11.     if (m_lpWord!=NULL)  
  12.     {  
  13.         try  
  14.         {  
  15.             m_lpWord->Release();  
  16.         }  
  17.         catch (...)  
  18.         {  
  19.         }  
  20.         m_lpWord = NULL;  
  21.     }  
  22. }  

本文主要是对MSWORD.OLB引入,这样可以很方便的使用msword的Word::_DocumentPtr类,更容易操作word,比如插入文字,表格修改,文档保存等,其实这就是vba在vc(或c++)的使用,当然下一篇将介绍在网页中利用activex控件打开word,以及利用IDispatch* 同时支持word/wps
### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值