原创文章转载请注明出处:@协思, http://zeeman.VEVb.com
得益于微软系强大的共通能力和Visual Studio的开发支持,做Office插件不是什么难事。一点经验记录如下:
1. 如果要同时开发Word和Outlook插件,那么可将复用的代码封闭到独立的Library中。
2. 在可安装.NET Framework 4的系统上,可以嵌入WPF组件。
3. 由于Office的安全模型,安装部署里需要可信任证书的签名。
4. 初始化代码可在ThisAddIn添加,如Startup、Shutdown、application.NewMailEx...
代码集锦
1. 获取文件名:
app = Globals.ThisAddIn.Application;Path.GetExtension(app.ActiveDocument.FullName)
2.检查文档是否保存:
app = Globals.ThisAddIn.Application;if (!app.ActiveDocument.Saved){ if (MessageBox.Show("This command publish the disk version of a file to the server. Do you want to save your changes to disk before PRoceeding?", "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { try { app.ActiveDocument.Save(); MessageBox.Show("save succeeded", "information", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("saved failed." + ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }}
3. 获取文档内容,并添加自己的信息
public byte[] GetDocumentContent(Word.Document wordDoc, string headerText, string footerText){ //使用Mail.RTFBody获取文档内容会丢失部分格式,所以这里还是采用剪贴板方式。 //复制文档内容到剪贴板 wordDoc.Content.Copy(); using (RichTextBox rtb = new RichTextBox()) { //添加头部信息 rtb.AppendText(headerText); rtb.SelectAll(); rtb.SelectionFont = new Font("Courier New", 11); rtb.SelectionColor = Color.Green; //添加正文 rtb.Select(rtb.TextLength, 0); rtb.Paste(); Clipboard.Clear(); //添加尾部信息 rtb.SelectionFont = new Font("Courier New", 11); rtb.SelectionColor = Color.Green; rtb.AppendText(footerText); using (System.IO.MemoryStream stream = new MemoryStream()) { rtb.SaveFile(stream, RichTextBoxStreamType.RichText); return stream.ToArray(); } }}
4. outlook邮件正文转换为word文档:
object selObject = currentExplorer.Selection[1];MailItem mail = selObject as MailItem;if (mail == null){ MessageBox.Show("non-mail item not supported.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return;}Word.Document wordDoc = (Word.Document)mail.GetInspector.WordEditor;
资源下载
Office Control Identifiers: http://www.microsoft.com/en-us/download/details.aspx?id=6627
Office Document Extractor: http://code.msdn.microsoft.com/office/CSOfficeDocumentFileExtract-e5afce86
新闻热点
疑难解答