private static void ConvertWordToPdf(string filePath) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string outputFilePath = OutputFolder + fileNameWithoutExtension + ".pdf"; Microsoft.Office.Interop.Word.ApplicationClass applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass(); Document document = null; try { document = applicationClass.Documents.Open(filePath); document.ExportAsFixedFormat(outputFilePath, WdExportFormat.wdExportFormatPDF); } catch (System.Exception e) { log.Error("Eccezione durante la conversione del file Word " + filePath); log.Error(e.StackTrace); File.Move(filePath, ErrorFolder + Path.GetFileName(filePath)); } finally { if (document != null) { document.Close(WdSaveOptions.wdDoNotSaveChanges); } if (applicationClass != null) { applicationClass.Quit(WdSaveOptions.wdDoNotSaveChanges); Marshal.FinalReleaseComObject(applicationClass); } CloseProcess("winword"); File.Delete(filePath); } }
/// <summary> /// 获取word页码数 /// </summary> /// <param name="strSourceFile">要转换的Word文档</param> /// <returns>页码数</returns> public int getWordPages(object strSourceFile) { try { int pages = 0; if (File.Exists(strSourceFile.ToString())) { object Nothing = System.Reflection.Missing.Value; //创建一个名为WordApp的组件对象 WORD.Application wordApp = new WORD.ApplicationClass(); //创建一个名为WordDoc的文档对象并打开 WORD.Document doc = wordApp.Documents.Open(ref strSourceFile, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //下面是取得打开文件的页数 pages = doc.ComputeStatistics(WORD.WdStatistic.wdStatisticPages, ref Nothing); //关闭文档对象 object saveOption = WORD.WdSaveOptions.wdDoNotSaveChanges; ((Microsoft.Office.Interop.Word._Document)doc).Close(ref saveOption, ref Nothing, ref Nothing); //推出组建 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); } return(pages); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); return(0); } }
public static bool LLenarDocumentoWord(object fileName, object saveAs, Dictionary<string,string> replace) { object missing = System.Reflection.Missing.Value; try { Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document aDoc = null; object readOnly = false, isVisible = false; wordApp.Visible = false; if (!File.Exists((string)fileName)) { MessageBox.Show("No existe el archivo " + fileName.ToString()); return false; } aDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); aDoc.Activate(); Dictionary<string, string>.KeyCollection fields = replace.Keys; foreach (string field in fields) { FindAndRepalce(wordApp, field, replace[field]); } //aDoc.Content.InsertBefore("Principio\r\n\r\n"); aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref missing, ref missing , ref missing, ref missing, ref missing, ref missing, ref missing, ref missing , ref missing, ref missing, ref missing, ref missing, ref missing); aDoc.Close(ref missing, ref missing, ref missing); return true; } catch (System.Runtime.InteropServices.COMException ex) { MessageBox.Show("Error al leer o crear el archivo. " + ex.Message); return false; } }
private void Load(string templateFile) { if (string.IsNullOrEmpty(templateFile)) { return; } object objFile = templateFile; Word.Application app = new Word.ApplicationClass(); try { Word.Document doc = app.Documents.Add(ref objFile); foreach (Word.Bookmark item in doc.Bookmarks) { lstBookMarks.Add(new BookMark(item.Name)); } doc.Close(); } catch (Exception) { } finally { //Close wordApp Component app.Quit(ref Nothing, ref Nothing, ref Nothing); } dgBookMarks.ItemsSource = lstBookMarks; }
} // cierre InsertScannedSignature private void SignWordDocument(string documentPath, string signatureFile, bool openWord) { WORD.ApplicationClass WordApp = new WORD.ApplicationClass(); try { object _missing = System.Reflection.Missing.Value; object _docPath = documentPath; WORD.Document adoc = WordApp.Documents.Open(ref _docPath, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing); object unit = 6; object move = 0; int _endKey = WordApp.Selection.EndKey(ref unit, ref move); // int _endOfDoc = WordApp.Selection.End; WordApp.Selection.InlineShapes.AddPicture(signatureFile, ref _missing, ref _missing, ref _missing); WordApp.Visible = openWord; } catch (Exception ex) { string _s = ex.ToString(); } finally { WordApp = null; } } // cierre SignWordDocument
/// <summary> /// word转成html /// </summary> /// <param name="wordFileName"></param> private string WordToHtml(object wordFileName, string htmlFileName) { object saveFileName = ""; try { //在此处放置用户代码以初始化页面 Word.ApplicationClass word = new Word.ApplicationClass(); Type wordType = word.GetType(); Word.Documents docs = word.Documents; //打开文件 Type docsType = docs.GetType(); Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true }); //转换格式,另存为 Type docType = doc.GetType(); string wordSaveFileName = wordFileName.ToString(); string strSaveFileName = htmlFileName; saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); } catch (Exception ex) { base.ClientScript.RegisterStartupScript(base.GetType(), null, string.Format("<script>alert('{0}');</script>", ex.Message.ToString())); } return(saveFileName.ToString()); }
/// <summary> /// 从模板创建新的Word文档, /// </summary> /// <param name="templateName">模板文件名</param> /// <param name="wDoc">返回的Word.Document对象</param> /// <param name="WApp">返回的Word.Application对象</param> /// <returns></returns> public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref Word.Application WApp) { Word.Document thisDocument = null; Word.Application thisApplication = new Word.ApplicationClass(); thisApplication.Visible = false; thisApplication.Caption = ""; thisApplication.Options.CheckSpellingAsYouType = false; thisApplication.Options.CheckGrammarAsYouType = false; Object Template = templateName;// Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used. Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False. Object DocumentType = Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument. Object Visible = true;//Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True. try { Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible); thisDocument = wordDoc; wDoc = wordDoc; WApp = thisApplication; return true; } catch (Exception ex) { string err = string.Format("创建Word文档出错,错误原因:{0}", ex.Message); throw new Exception(err, ex); } }
/// <summary> /// 把指定WORD转换成PDF /// </summary> /// <param name="strSourceFile">要转换的Word文档</param> /// <param name="strTargetFile">转换成的结果文件</param> /// <returns></returns> public bool WordConvertTOPDF(object strSourceFile, object strTargetFile) { try { bool flag = true; if (File.Exists(strSourceFile.ToString())) { object Nothing = System.Reflection.Missing.Value; //创建一个名为WordApp的组件对象 WORD.Application wordApp = new WORD.ApplicationClass(); //创建一个名为WordDoc的文档对象并打开 WORD.Document doc = wordApp.Documents.Open(ref strSourceFile, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //设置保存的格式 object filefarmat = WORD.WdSaveFormat.wdFormatPDF; //保存为PDF doc.SaveAs(ref strTargetFile, ref filefarmat, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //关闭文档对象 object saveOption = WORD.WdSaveOptions.wdDoNotSaveChanges; ((Microsoft.Office.Interop.Word._Document)doc).Close(ref saveOption, ref Nothing, ref Nothing); //推出组建 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); } return(flag); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); return(false); } }
public static void WordToHtml(string sourceFileName, string targetFileName) { Microsoft.Office.Interop.Word.ApplicationClass WordApp; Microsoft.Office.Interop.Word.Document WordDoc; Object oMissing = System.Reflection.Missing.Value; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); object fileName = sourceFileName; WordDoc = WordApp.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); try { Type wordType = WordApp.GetType(); // 打开文件 Type docsType = WordApp.Documents.GetType(); // 转换格式,另存为 Type docType = WordDoc.GetType(); object saveFileName = targetFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML }); } finally { WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); } }
public static void ConvertToPDF(String filePath, String destpath) { // file exist & check type if (!filePath.IsNormalized() || !File.Exists(filePath)) { throw new Exception("未指定文件"); } if (!filePath.EndsWith("doc") && !filePath.EndsWith("docx")) { throw new Exception("文件非 word 类型"); } Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(filePath); doc.ExportAsFixedFormat(destpath, WdExportFormat.wdExportFormatPDF); // rename List <String> list = new List <string>(); String[] fileNames = Directory.GetFiles(destpath); foreach (var fileName in fileNames) { String newFileName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName)); File.Move(fileName, newFileName); list.Add(newFileName); } }
private int GetLcid() { // System.Windows.Forms.MessageBox.Show("modify lcid"); // add by huizhong , modify the language id in templates XML files for different office version (2052 for Chinese and 1033 for English) int lcid = 1033; try { Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.ApplicationClass(); LanguageSettings languageSettings = (LanguageSettings)thisApplication.LanguageSettings; lcid = languageSettings.get_LanguageID(MsoAppLanguageID.msoLanguageIDUI); object missing = Type.Missing; thisApplication.Quit(ref missing, ref missing, ref missing);//dispose the winword thisApplication = null; GC.Collect(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); //System.Windows.Forms.MessageBox.show("lcid=" + lcid); } return(lcid); }
/// <summary> /// word转成html /// </summary> /// <param name="wordFileName">绝对地址</param> public static string wordToHtml(object wordFileName) { try { //判断文件夹是否存在(不存在创建一个) if (!Directory.Exists(HttpContext.Current.Server.MapPath("/WordToHtml"))) { new DirectoryInfo(HttpContext.Current.Server.MapPath("/WordToHtml")).Create(); } //在此处放置用户代码以初始化页面 Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = word.GetType(); Microsoft.Office.Interop.Word.Documents docs = word.Documents; //打开文件 Type docsType = docs.GetType(); Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true }); //转换格式,另存为 Type docType = doc.GetType(); string wordSaveFileName = wordFileName.ToString(); string strSaveFileName = ""; strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html"; object saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); return(saveFileName.ToString()); } catch (Exception ex) { LogHelper.WriteLog(Convert.ToString("Word错误:" + ex.Message + "------------------------------------" + ex.StackTrace)); throw new Exception(ex.Message, ex); } }
//public static int GetWordPageCount1(string path) //{ // XWPFDocument m_Docx = new XWPFDocument(); // m_Docx. // System.IO.File doc = File("/Users/oushuuryuu/Desktop", "rirekisyo_jis.doc"); // Stream inStream = new FileStream(doc); // m_Docx.Document.GetHashCode(); // //File doc = new System.IO.File("/Users/oushuuryuu/Desktop", "rirekisyo_jis.doc"); // var document = DocX.Load(path); // Stream stream = new FileStream(); // MemoryStream stream2 = new MemoryStream(); // PostCreation(ref Package.Open(stream2, FileMode.Create, FileAccess.ReadWrite)); // Docx cx= Load(stream2); // cx.stream = stream; //} #region --获取word文件的页数-- /// <summary> /// 获得word文档页数 /// </summary> /// <param name="path"></param> /// <returns></returns> public int GetWordPageCount(string path) { //try //{ Microsoft.Office.Interop.Word.Application myWord = new Microsoft.Office.Interop.Word.ApplicationClass(); object oMiss = System.Reflection.Missing.Value; myWord.Visible = false; object filePath = path; //这里是Word文件的路径 //打开文件 Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open( ref filePath, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss); //下面是取得打开文件的页数 int pages = myWordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMiss); myWordDoc.Close(ref oMiss, ref oMiss, ref oMiss); return(pages); //} //catch (Exception ex) //{ // return 0; //} }
/// <summary> /// 从模板创建新的Word文档, /// </summary> /// <param name="templateName">模板文件名</param> /// <param name="wDoc">返回的Word.Document对象</param> /// <param name="WApp">返回的Word.Application对象</param> /// <returns></returns> public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref Word.Application WApp) { Word.Document thisDocument = null; Word.Application thisApplication = new Word.ApplicationClass(); thisApplication.Visible = false; thisApplication.Caption = ""; thisApplication.Options.CheckSpellingAsYouType = false; thisApplication.Options.CheckGrammarAsYouType = false; Object Template = templateName; // Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used. Object NewTemplate = false; // Optional Object. True to open the document as a template. The default value is False. Object DocumentType = Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument. Object Visible = true; //Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True. try { Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible); thisDocument = wordDoc; wDoc = wordDoc; WApp = thisApplication; return(true); } catch (Exception ex) { string err = string.Format("创建Word文档出错,错误原因:{0}", ex.Message); throw new Exception(err, ex); } }
/// <summary> /// Preactivation /// It's usefull, if you need more speed in the main Program /// so you can preload Word. /// </summary> public void PreActivate() { if (wd == null) { wd = new Word.ApplicationClass(); } }
public static void Word2Pdf(string path, string savepath) { var word = new Word.ApplicationClass(); var wordType = word.GetType(); var docs = word.Documents; var docsType = docs.GetType(); var doc = (Word.Document)docsType.InvokeMember( "Open", BindingFlags.InvokeMethod, null, docs, new[] { (object)path, true, true }); var docType = doc.GetType(); docType.InvokeMember( "SaveAs", BindingFlags.InvokeMethod, null, doc, new[] { (object)savepath, Word.WdSaveFormat.wdFormatPDF }); docType.InvokeMember( "Close", BindingFlags.InvokeMethod, null, doc, new object[] { Word.WdSaveOptions.wdDoNotSaveChanges }); wordType.InvokeMember( "Quit", BindingFlags.InvokeMethod, null, word, null); }
public void GetWord(string strContent) { object path;//文件路径 MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量 path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordApp.Selection.ParagraphFormat.LineSpacing = 35f;//设置文档的行间距 //写入普通文本 wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度 wordDoc.Paragraphs.Last.Range.Text = strContent; object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); }
/// <summary> /// Button click event for submitting the entaire form data into the mail /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void submitbutton_Click(object sender, EventArgs e) { // Convert text format to html format string text = txtformat.Text; string M = Regex.Replace(text, @"<(.|\n)*?>", string.Empty); string Mar = M.Replace(" ", " "); string[] split = Mar.Split(new Char[] { ' ', ',', '.', ':', '\t' }, StringSplitOptions.RemoveEmptyEntries); string[] Sid = M.Split(split, StringSplitOptions.RemoveEmptyEntries); // string filename = split[0].ToString() + ".docx"; string dttym = DateTime.Now.ToString("dd-MMM-yyyy") + "_" + DateTime.Now.ToString("HH-mm-ss"); string filename = split[0].ToString() + dttym + ".docx"; //object fileName = Server.MapPath(@".\Docs\") + filename; object fileName = Server.MapPath("~/Docs/") + filename; object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document oWordDoc = oWordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); oWordDoc.Activate(); oWordApp.Selection.TypeText(text); oWordApp.Selection.TypeParagraph(); oWordDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); oWordDoc.Close(ref missing, ref missing, ref missing); oWordApp.Application.Quit(ref missing, ref missing, ref missing); }
public void output() { string content; MSWord.Application wordApp; MSWord.Document wordDoc; object filePath = Server.MapPath("/") + "weekCalWord\\" + @"\testWord.docx"; wordApp = new MSWord.ApplicationClass(); if (File.Exists(filePath.ToString())) { File.Delete(filePath.ToString()); } Object nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 6, 6, ref nothing, ref nothing); table.Borders.Enable = 1; for (int i = 1; i < 6; i++) { for (int j = 1; j < 6; j++) { table.Cell(i, j).Range.Text = i.ToString() + "行" + j.ToString() + "列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列列?~p列列列列列列列列列列列列列列列列"; } } object format = MSWord.WdSaveFormat.wdFormatDocument; object oMissing = System.Reflection.Missing.Value; wordDoc.SaveAs(ref filePath, ref oMissing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); wordDoc.Close(ref nothing, ref nothing, ref nothing); wordApp.Quit(ref nothing, ref nothing, ref nothing); }
public void PastTest() { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass(); app.Visible = false; Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"C:\Users\Administrator\Desktop\WorkFiles\Letter Automation\Template\NewTemplate\(chi) Cancellation of PW1.doc", false); doc.Activate(); doc.Tables[2].Cell(2, 2).Range.FormFields[1].Result = "44444444"; int count = doc.FormFields.Count; doc.Tables[1].ConvertToText(WdTableFieldSeparator.wdSeparateByParagraphs, false); doc.Tables[2].Cell(1, 3).Range.Text = "33"; doc.Tables[3].Rows.Add(); object unite = WdUnits.wdStory; app.Selection.EndKey(ref unite, Type.Missing); //将光标移动到文档末尾 doc.Tables[3].Rows[1].Cells[1].Range.Paste(); doc.Tables[3].Rows.Add(); doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, Type.Missing, Type.Missing, true); doc.Save(); doc.Save(); doc.Close(); app.Quit(); }
public static void ConvertToPDFWithPrinter(String filePath, String destpath) { // file exist & check type if (!filePath.IsNormalized() || !File.Exists(filePath)) { throw new Exception("未指定文件"); } if (!filePath.EndsWith("doc") && !filePath.EndsWith("docx")) { throw new Exception("文件非 word 类型"); } Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = word.GetType(); Microsoft.Office.Interop.Word.Documents docs = word.Documents; Type docsType = docs.GetType(); Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { filePath, true, true }); doc.Application.ActivePrinter = "Microsoft Print to PDF"; Type docType = doc.GetType(); docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { false, false, Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument, destpath }); wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); }
public TechDoc2(string TemplateFilename, bool Visible) { CurrentTechSection = 0; CurrentTechLine = 0; ItemSectionFormat = "{0}. "; ItemLineFormat = "{0}.{1}. "; WORDApp = new Word.ApplicationClass(); WORDApp.Visible = true; object useDefaultValue = Type.Missing; object visible = Visible; object template = TemplateFilename; doc = WORDApp.Documents.Add(ref template, ref useDefaultValue, ref useDefaultValue, ref visible); //настройка стилей Word.Style SectionStyle = doc.Styles[Word.WdBuiltinStyle.wdStyleHeading1]; SectionStyle.Font.Color = Word.WdColor.wdColorBlack; SectionStyle.Font.Name = "Calibri"; SectionStyle.Font.Size = 16; Word.Style NormalStyle = doc.Styles[Word.WdBuiltinStyle.wdStyleNormal]; NormalStyle.Font.Color = Word.WdColor.wdColorBlack; NormalStyle.Font.Name = "Calibri"; NormalStyle.Font.Size = 12; //список таблиц документа TablesList = new Dictionary<string, Word.Table>(); //список литературы BiblioList = new List<BiblioSource>(); }
private static string ParseWordToText(string inputFile, string outputFile) { try { var wordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); string fn = inputFile; object oFile = fn; object oNull = System.Reflection.Missing.Value; object oReadOnly = true; var Doc = wordApp.Documents.Open(ref oFile, ref oNull, ref oReadOnly, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull, ref oNull); var result = Doc.Paragraphs.Cast <Paragraph>().Aggregate(string.Empty, (current, oPara) => current + oPara.Range.Text); using (var sw = new StreamWriter(outputFile)) { sw.WriteLine(result); } wordApp.Quit(ref oNull, ref oNull, ref oNull); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(string.Empty); }
/// <summary> /// 把Word文件转换成pdf文件2 /// </summary> /// <param name="sourcePath">需要转换的文件路径和文件名称</param> /// <param name="targetPath">转换完成后的文件的路径和文件名名称</param> /// <returns>成功返回true,失败返回false</returns> public static bool WordToPdf(object sourcePath, string targetPath) { bool result = false; WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF; object missing = Type.Missing; Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null; Microsoft.Office.Interop.Word.Document document = null; try { applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass(); document = applicationClass.Documents.Open(ref sourcePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); if (document != null) { document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing); } result = true; } catch { result = false; } finally { if (document != null) { document.Close(ref missing, ref missing, ref missing); document = null; } if (applicationClass != null) { applicationClass.Quit(ref missing, ref missing, ref missing); applicationClass = null; } } return result; }
/// <summary> /// 化验单 /// </summary> /// <param name="a"></param> private void PrintAssay(Assay a) { Log.Logs += $"正在打印化验单:{a.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintAssayDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", a.Name); if (a.Purchase != null) { WordReplace(wApp, "#CarnoOrStorename#", "车号:" + a.Purchase.CarNo); } if (a.Store != null) { WordReplace(wApp, "#CarnoOrStorename#", "油仓:" + a.Store.Name); } WordReplace(wApp, "#视密#", a.视密.ToString("0.000")); WordReplace(wApp, "#标密#", a.标密.ToString("0.000")); WordReplace(wApp, "#闭口闪点#", a.闭口闪点); WordReplace(wApp, "#Temperature#", a.Temperature.ToString("0.00")); WordReplace(wApp, "#OilTempTime#", a.OilTempTime.ToLongTimeString()); WordReplace(wApp, "#SmellType#", strSmellType(a.SmellType)); WordReplace(wApp, "#混水反应#", a.混水反应); WordReplace(wApp, "#十六烷值#", a.十六烷值); WordReplace(wApp, "#十六烷指数#", a.十六烷指数); WordReplace(wApp, "#初硫#", a.初硫.ToString("0.00")); WordReplace(wApp, "#Percentage10#", a.Percentage10.ToString("0.00")); WordReplace(wApp, "#Percentage50#", a.Percentage50.ToString("0.00")); WordReplace(wApp, "#Percentage90#", a.Percentage90.ToString("0.00")); WordReplace(wApp, "#回流#", a.回流.ToString("0.00")); WordReplace(wApp, "#干点#", a.干点.ToString("0.00")); WordReplace(wApp, "#蚀点#", a.蚀点.ToString("0.00")); WordReplace(wApp, "#凝点#", a.凝点.ToString("0.00")); WordReplace(wApp, "#含硫#", a.含硫.ToString("0.00")); WordReplace(wApp, "#CreatedBy#", a.CreatedBy); WordReplace(wApp, "#CreatedAt#", a.CreatedAt.ToString("yyyy-MM-dd HH:mm")); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + a.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
//public static void createNewWord(Object path, DataTable list_tables) //{ // msword.Application tableApp = new msword.ApplicationClass(); // object nothing = Missing.Value; // msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); // //msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, 3, 2, ref nothing, ref nothing); // msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables.Rows.Count + 1, list_tables.Columns.Count, ref nothing, ref nothing); // table.Borders.Enable = 1; // table.Borders.OutsideLineStyle = msword.WdLineStyle.wdLineStyleSingle; // for (int l = 0; l < list_tables.Columns.Count; l++) // { // table.Cell(1, l + 1).Range.Text = list_tables.Columns[l].ColumnName; // } // for (int i = 0; i < list_tables.Rows.Count; i++) // { // for (int j = 0; j < list_tables.Columns.Count; j++) // { // table.Cell(i + 2, j + 1).Range.Text = list_tables.Rows[i][j].ToString(); // } // } // object moveUnit = msword.WdUnits.wdLine; // object moveCount = list_tables.Rows.Count*2+2; // table.Cell(1, 1).Range.Select(); //获取焦点 // tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing); // tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing); // tableApp.Selection.TypeParagraph(); // //插入图片 // string FileName = Application.StartupPath + @"\Image\2.jpg";//图片所在路径 // object LinkToFile = false; // object SaveWithDocument = true; // object Anchor = wordDoc.Paragraphs.Last.Range; // //object Anchor = tableApp.Selection.Range; // wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); // msword.Table table2 = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables.Rows.Count + 1, list_tables.Columns.Count, ref nothing, ref nothing); // table2.Borders.Enable = 1; // table2.Borders.OutsideLineStyle = msword.WdLineStyle.wdLineStyleSingle; // for (int l = 0; l < list_tables.Columns.Count; l++) // { // table2.Cell(1, l + 1).Range.Text = list_tables.Columns[l].ColumnName; // } // for (int i = 0; i < list_tables.Rows.Count; i++) // { // for (int j = 0; j < list_tables.Columns.Count; j++) // { // table2.Cell(i + 2, j + 1).Range.Text = list_tables.Rows[i][j].ToString(); // } // } // /*3、导入模板 // object oMissing = System.Reflection.Missing.Value; // Word._Application oWord; // Word._Document oDoc; // oWord = new Word.Application(); // oWord.Visible = true; // object fileName = @"E:XXXCCXTest.doc"; // oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);*/ // //wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度 // //wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度 // //将图片设置为四周环绕型 // //Microsoft.Office.Interop.Word.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); // // s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; // object format = msword.WdSaveFormat.wdFormatDocumentDefault; // wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); // wordDoc.Close(ref nothing, ref nothing, ref nothing); // tableApp.Quit(ref nothing, ref nothing, ref nothing); //} //public static void createNewWord2(Object path, List<DataTable> list_tables,string image_path) //{ // msword.Application tableApp = new msword.ApplicationClass(); // object nothing = Missing.Value; // msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); // //msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, 3, 2, ref nothing, ref nothing); // for (int k = 0; k < list_tables.Count; k++) // { // msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables[k].Rows.Count + 1, list_tables[k].Columns.Count, ref nothing, ref nothing); // table.Borders.Enable = 1; // table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; // for (int l = 0; l < list_tables[k].Columns.Count; l++) // { // table.Cell(1, l + 1).Range.Text = list_tables[k].Columns[l].ColumnName; // } // for (int i = 0; i < list_tables[k].Rows.Count; i++) // { // for (int j = 0; j < list_tables[k].Columns.Count; j++) // { // table.Cell(i + 2, j + 1).Range.Text = list_tables[k].Rows[i][j].ToString(); // } // } // object moveUnit = msword.WdUnits.wdLine; // object moveCount = list_tables[k].Rows.Count * 2 + 2; // table.Cell(1, 1).Range.Select(); //获取焦点 // object dummy = System.Reflection.Missing.Value; // object what = msword.WdGoToItem.wdGoToLine; // object which = msword.WdGoToDirection.wdGoToFirst; // object count = list_tables[k].Rows.Count+1; // wordDoc.Application.ActiveDocument.GoTo(ref what, ref which, ref count, ref dummy); // //tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing); // //tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing); // //tableApp.Selection.TypeParagraph(); // //OperatePicture.ExportPicture(list_types[k]+"_PLOT"); // //插入图片 // string FileName = image_path;//图片所在路径 // object LinkToFile = false; // object SaveWithDocument = true; // //object Anchor = wordDoc.Paragraphs.Last.Range; // object Anchor = wordDoc.Paragraphs.Last.Range; // wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); // } // object format = msword.WdSaveFormat.wdFormatDocumentDefault; // wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); // wordDoc.Close(ref nothing, ref nothing, ref nothing); // tableApp.Quit(ref nothing, ref nothing, ref nothing); //} #endregion public static void createNewWord3(Object path, Dictionary <DataTable, string> dicts) { msword.Application tableApp = new msword.ApplicationClass(); object nothing = Missing.Value; msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); foreach (KeyValuePair <DataTable, string> pair in dicts) { //wordDoc.Application.Selection.TypeParagraph(); //wordDoc.Application.Selection.TypeText("表一"); //wordDoc.Application.Selection.TypeParagraph(); DataTable item = pair.Key; msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, item.Rows.Count + 1, item.Columns.Count, ref nothing, ref nothing); table.Borders.Enable = 1; table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; for (int l = 0; l < item.Columns.Count; l++) { table.Cell(1, l + 1).Range.Text = item.Columns[l].ColumnName; } for (int i = 0; i < item.Rows.Count; i++) { for (int j = 0; j < item.Columns.Count; j++) { table.Cell(i + 2, j + 1).Range.Text = item.Rows[i][j].ToString(); } } //wordDoc.Application.Selection.Font.Size = 16; //wordDoc.Application.Selection.Font.Size = 10; //wordDoc.Application.Selection.Font.Bold = 10; object moveUnit = msword.WdUnits.wdLine; object moveCount = 2; //table.Cell(1, 1).Range.Select(); //获取焦点 table.Select(); tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing); //tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing); tableApp.Selection.TypeParagraph(); //tableApp.Selection.TypeParagraph(); //OperatePicture.ExportPicture(list_types[k]+"_PLOT"); //插入图片 string FileName = pair.Value;//图片所在路径 if (!string.IsNullOrEmpty(FileName)) { object LinkToFile = false; object SaveWithDocument = true; //object Anchor = wordDoc.Paragraphs.Last.Range; object Anchor = wordDoc.Paragraphs.Last.Range; wordDoc.Application.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument); //wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); } } object format = msword.WdSaveFormat.wdFormatDocumentDefault; wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); wordDoc.Close(ref nothing, ref nothing, ref nothing); tableApp.Quit(ref nothing, ref nothing, ref nothing); }
private void SaveCrossReport(object sender, RoutedEventArgs e) { object missing = System.Reflection.Missing.Value; Word.ApplicationClass WordApp = new Word.ApplicationClass(); Word.Document doc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); Word.Range range = doc.Range(0, ref missing); SaveFileDialog dialog = new SaveFileDialog() { Filter = "Word Files (*doc)|*.doc;" }; if (dialog.ShowDialog() == true) { object fileName = dialog.FileName; try { range.Font.Name = "Georgia"; range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; range.Font.Size = 14.0F; range.Font.Bold = 1; range.Font.Underline = Word.WdUnderline.wdUnderlineSingle; range.InsertAfter("Перекрестная статистика по художникам\n\n"); range.Font.Underline = Word.WdUnderline.wdUnderlineNone; var table = range.Tables.Add(range.Paragraphs[2].Range, CrossView.Table.Rows.Count + 1, CrossView.Table.Columns.Count, ref missing, ref missing); range.Tables[1].Range.Font.Size = 10; range.Tables[1].Range.Font.Name = "Consolas"; range.Tables[1].Range.Font.Bold = 0; range.Tables[1].Columns.DistributeWidth(); range.Tables[1].Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; range.Tables[1].Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; for (int i = 0; i < CrossView.Table.Columns.Count; i++) { range.Tables[1].Cell(1, i + 1).Range.Text = CrossView.Table.Columns[i].ColumnName; } for (int k = 0; k < CrossView.Table.Rows.Count; k++) { var items = CrossView.Table.Rows[k].ItemArray; for (int i = 0; i < items.Length; i++) { range.Tables[1].Cell(k + 2, i + 1).Range.Text = items[i].ToString(); } } range.InsertAfter("\nDate:" + DateTime.Now.ToString()); doc.SaveAs2(ref fileName); WordApp.Visible = true; } catch (Exception ex) { MessageBox.Show("Создать отчет не удалось. Ошибка: " + ex.Message); } } }
public static void createNewWord3(Object path, Dictionary<DataTable,string> dicts) { msword.Application tableApp = new msword.ApplicationClass(); object nothing = Missing.Value; msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); foreach (KeyValuePair<DataTable,string> pair in dicts) { //wordDoc.Application.Selection.TypeParagraph(); //wordDoc.Application.Selection.TypeText("表一"); //wordDoc.Application.Selection.TypeParagraph(); DataTable item = pair.Key; msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, item.Rows.Count + 1, item.Columns.Count, ref nothing, ref nothing); table.Borders.Enable = 1; table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; for (int l = 0; l < item.Columns.Count; l++) { table.Cell(1, l + 1).Range.Text = item.Columns[l].ColumnName; } for (int i = 0; i < item.Rows.Count; i++) { for (int j = 0; j < item.Columns.Count; j++) { table.Cell(i + 2, j + 1).Range.Text = item.Rows[i][j].ToString(); } } //wordDoc.Application.Selection.Font.Size = 16; //wordDoc.Application.Selection.Font.Size = 10; //wordDoc.Application.Selection.Font.Bold = 10; object moveUnit = msword.WdUnits.wdLine; object moveCount = 2; //table.Cell(1, 1).Range.Select(); //获取焦点 table.Select(); tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing); //tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing); tableApp.Selection.TypeParagraph(); //tableApp.Selection.TypeParagraph(); //OperatePicture.ExportPicture(list_types[k]+"_PLOT"); //插入图片 string FileName =pair.Value;//图片所在路径 if (!string.IsNullOrEmpty(FileName)) { object LinkToFile = false; object SaveWithDocument = true; //object Anchor = wordDoc.Paragraphs.Last.Range; object Anchor = wordDoc.Paragraphs.Last.Range; wordDoc.Application.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument); //wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); } } object format = msword.WdSaveFormat.wdFormatDocumentDefault; wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); wordDoc.Close(ref nothing, ref nothing, ref nothing); tableApp.Quit(ref nothing, ref nothing, ref nothing); }
/// <summary> /// 陆上装车单 /// </summary> /// <param name="order">model</param> private void PrintLandLoad(Order order) { Log.Logs += $"正在打印LoadOil:{order.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintLandLoadDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 decimal DiffWeightToLitre = order.DiffWeight / (decimal)order.Density * 1000; decimal OilCountTon = order.OilCountLitre * (decimal)order.Density / 1000; decimal DiffPondLitre = order.OilCountLitre - DiffWeightToLitre; //填充数据 WordReplace(wApp, "#Name#", order.Name); WordReplace(wApp, "#ClientName#", order.Client.CarNo); WordReplace(wApp, "#CompanyName#", order.Client.Company?.Name); WordReplace(wApp, "#StoreName#", order.Store.Name); WordReplace(wApp, "#DiffWeight#", order.DiffWeight.ToString("0.0")); WordReplace(wApp, "#Count#", (order.Count * 1000).ToString("0.0")); WordReplace(wApp, "#DiffOrder#", (order.DiffWeight - order.Count * 1000).ToString("0.0")); WordReplace(wApp, "#Price#", order.IsPrintPrice? order.Price.ToString() : "0.00"); WordReplace(wApp, "#TotalMoney#", order.TotalMoney.ToString()); WordReplace(wApp, "#OilCount#", order.OilCountLitre.ToString()); WordReplace(wApp, "#OilCountTon#", OilCountTon.ToString("0.0")); WordReplace(wApp, "#DiffWeight#", (order.OilCarWeight - order.EmptyCarWeight).ToString("0.0")); WordReplace(wApp, "#DiffWeightTon#", ((order.OilCarWeight - order.EmptyCarWeight) / 1000).ToString("0.0")); WordReplace(wApp, "#DiffWeightToLitre#", DiffWeightToLitre.ToString("0.00")); WordReplace(wApp, "#DiffPondLitre#", DiffPondLitre.ToString("0.0")); WordReplace(wApp, "#DiffPondTon#", (DiffPondLitre * (decimal)order.Density / 1000).ToString("0.0")); WordReplace(wApp, "#Instrument_bf#", (order.Instrument1 - order.OilCountLitre).ToString()); WordReplace(wApp, "#Instrument_af#", order.Instrument1.ToString()); WordReplace(wApp, "#Density#", order.Density.ToString("0.000")); WordReplace(wApp, "#OilTemperature#", order.OilTemperature.ToString()); WordReplace(wApp, "#Worker#", order.Worker); WordReplace(wApp, "#LastUpdatedAt#", order.LastUpdatedAt.ToString()); WordReplace(wApp, "#Salesman#", order.Salesman); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + order.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
private static void ComputeStatistics() { int pagecount = 0; int wordcount = 0; object fileName = Filename; object readOnly = false; object isVisible = false; object objDNS = Word.WdSaveOptions.wdPromptToSaveChanges; object missing = System.Reflection.Missing.Value; Word._Application WordApp = new Word.ApplicationClass(); Word._Document aDoc = null; try { aDoc = WordApp.Documents.Open ( ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing ); Word.WdStatistic pagestat = Word.WdStatistic.wdStatisticPages; Word.WdStatistic wordstat = Word.WdStatistic.wdStatisticWords; pagecount = aDoc.ComputeStatistics(pagestat, ref missing); wordcount = aDoc.ComputeStatistics(wordstat, ref missing); } catch (Exception ex) { } finally { if (aDoc != null) { aDoc.Close(ref objDNS, ref missing, ref missing); Marshal.ReleaseComObject(aDoc); aDoc = null; } if (WordApp != null) { WordApp.Quit(ref objDNS, ref missing, ref missing); Marshal.ReleaseComObject(WordApp); WordApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); } TotalPages = pagecount; NoOfWords = wordcount; }
private void PrintUnload(Purchase p) { Log.Logs += $"正在打印陆上卸油单:{p.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintUnloadDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", p.Name); WordReplace(wApp, "#CarNo#", p.CarNo); WordReplace(wApp, "#ProductName#", p.Product?.Name); WordReplace(wApp, "#Count#", p.Count.ToString()); WordReplace(wApp, "#OilCount#", p.OilCount.ToString("0.00")); WordReplace(wApp, "#Density#", p.Density.ToString("0.000")); WordReplace(wApp, "#ScaleWithCar#", p.ScaleWithCar.ToString()); WordReplace(wApp, "#Scale#", p.Scale.ToString()); string strToStore = ""; foreach (var st in p.ToStoresList) { strToStore += "\r"; strToStore += "卸入仓:" + st.Name + "\r"; strToStore += "卸油前表数:" + st.InstrumentBf + "\r"; strToStore += "卸油后表数:" + st.InstrumentAf + "\r"; strToStore += "卸油数量:" + st.Count + "升\r"; } WordReplace(wApp, "#ToStores#", strToStore); WordReplace(wApp, "#DiffLitre#", p.DiffLitre.ToString("0.00")); WordReplace(wApp, "#DiffTon#", p.DiffTon.ToString("0.00")); WordReplace(wApp, "#Worker#", p.Worker); WordReplace(wApp, "#StartTime#", p.StartTime.HasValue ? DateTime.Parse(p.StartTime.ToString()).ToString("yyyy-MM-dd HH:mm") : ""); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + p.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
//// This Regex pattern matches formatting tags that are used in text elements (e.g., <tag></tag> or <tag/>). //private const string xmlTagPattern = @"\<(?<slash>/)?[a-zA-Z]+(?!\k<slash>)/?\>"; /// <summary>Creates a new instance of <see cref="Spellchecker"/>.</summary> public Spellchecker() { // Activate Word _WordApp = new Word.ApplicationClass(); _WordDoc = _WordApp.Documents.Add(ref _Missing, ref _Missing, ref _Missing, ref _Missing); // On Windows 7, starting Word causes the ArcMap window to be sent behind other open windows. // Then, when the SpellCheck dialog was shown, it would also be hidden behind the other windows. ActivateArcMap(); }
public void Navigate(string filename) { if (filename.Equals("about:blank") && wd != null && wd.Documents.Count > 0) { try { deactivateevents = true; object obj = 1; Word.Document tempDoc = wd.Documents[obj]; object objSaveOption = Word.WdSaveOptions.wdDoNotSaveChanges; object oMissing = System.Reflection.Missing.Value; Word.Application wordApp = tempDoc.Application; tempDoc.Close(objSaveOption, oMissing, oMissing); wordApp.Quit(objSaveOption, oMissing, oMissing); } catch (Exception) { } finally { deactivateevents = false; } try { CloseControl(); } catch (Exception) { } finally { document = null; wd = null; hOffset = -1; wordWnd = 0; } //this.CloseControl(); return; } try { CloseControl(); } catch (Exception) { } finally { document = null; wd = null; hOffset = -1; wordWnd = 0; } Word.Document doc = this.LoadDocument(filename); if (delLoadFileFinished != null) { delLoadFileFinished.Invoke(doc); } }
/// <summary> /// word内容查找 /// </summary> /// <param name="fileFullPath">文件全路径</param> /// <param name="searchValue">查找内容</param> /// <returns></returns> public static bool CheckWordContent(string fileFullPath, string searchValue) { object filename = fileFullPath; //要打开的文档路径 string strKey = searchValue; //要搜索的文本 object MissingValue = Type.Missing; bool checkResult = false; int i = 0, iCount = 0; if (fileFullPath.Contains("~$")) { return(checkResult); } Microsoft.Office.Interop.Word.Find wfnd; Microsoft.Office.Interop.Word.Application wp = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = wp.GetType(); wp.Visible = false; Document wd = wp.Documents.Open(ref filename, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); //查找 if (wd.Paragraphs != null && wd.Paragraphs.Count > 0) { iCount = wd.Paragraphs.Count; for (i = 1; i <= iCount; i++) { wfnd = wd.Paragraphs[i].Range.Find; wfnd.ClearFormatting(); wfnd.Text = strKey; if (wfnd.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { checkResult = true; break; } } } //Application退出 wp.Quit(ref MissingValue, ref MissingValue, ref MissingValue); return(checkResult); }
private Word.Document oDoc; // a reference to the document public CCWordApp() { try { oWordApplic = new Word.ApplicationClass(); } catch (Exception ex) { CreateLogTxt.ErrWriter(ex); } }
/// <summary> /// 调拨单 也是收款单 水上陆上共用 /// </summary> /// <param name="order"></param> private void PrintOrder(Order order) { Log.Logs += $"正在打印Order:{order.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintOrderDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", order.Name); WordReplace(wApp, "#CarNo#", order.CarNo); WordReplace(wApp, "#ProductName#", "石化油"); WordReplace(wApp, "#Count#", order.Count.ToString()); WordReplace(wApp, "#Unit#", order.Unit); WordReplace(wApp, "#Price#", order.IsPrintPrice ? order.Price.ToString("0.00") : ""); WordReplace(wApp, "#TotalMoney#", order.IsPrintPrice? order.TotalMoney.ToString("0.00") : ""); WordReplace(wApp, "#Payments#", strPayments(order.Payments.ToList())); WordReplace(wApp, "#CNMoney#", ConvertToChinese(order.TotalMoney)); WordReplace(wApp, "#Remark#", order.Remark); WordReplace(wApp, "#LastUpdatedBy#", order.Cashier); WordReplace(wApp, "#Salesman#", order.Salesman); WordReplace(wApp, "#CreatedAt#", order.CreatedAt.ToString("yyyy-MM-dd HH:mm")); PrintTime(wApp); string strInvoice = ""; if (order.IsInvoice) { strInvoice += "开票单位:" + order.BillingCompany + "\r"; strInvoice += "开票单价:¥" + order.BillingPrice + "\r"; strInvoice += "开票数量:" + order.BillingCount + order.Unit + "\r"; //strInvoice += "类型:" + strTicketType(order.TicketType); } WordReplace(wApp, "#InvoiceContent#", strInvoice); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + order.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
public void cant_load_playlist_newFormat() { object template = BB080627; object isNewTemplate = false; object documentType = WdNewDocumentType.wdNewBlankDocument; object isVisible = false; Microsoft.Office.Interop.Word.ApplicationClass app = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(ref template, ref isNewTemplate, ref documentType, ref isVisible); Playlist playlist = new Playlist("x"); IList<Einsatz> einsaetze = new List<Einsatz>(); for(int i = 3; i <= doc.Tables[1].Rows.Count - 1; i++) { Row row = doc.Tables[1].Rows[i]; Track track = new Track( new Autor(" "), new Bpm(null), new Code(init(brush(row.Cells[4].Range.Text))), new Interpret(init(brush(row.Cells[5].Range.Text))), new Label(init(brush(row.Cells[3].Range.Text))), new Laenge(init(brush(row.Cells[7].Range.Text))), new Titel(init(brush(row.Cells[1].Range.Text))), new Verlag(" "), new Year(null), new Ending(Ending.Attribute.None)); einsaetze.Add(new Einsatz(playlist, track, row.Index - 2)); } /* * One dataset is actually missing. */ Assert.AreNotEqual(doc.Tables[1].Rows.Count - 2, einsaetze.Count); /* * Do throw PostconditionException! */ Check.Ensure(doc.Tables[1].Rows.Count - 2 == einsaetze.Count, String.Format("Playlist unvollstaendig! Lesbare Datensaezte: {0} von {1}.", einsaetze.Count, doc.Tables[1].Rows.Count - 2)); }
/// <summary> /// word转成html /// </summary> /// <param name="sourceDir"></param> /// <param name="name"></param> /// <param name="targetDir"></param> public static string WordToHtml(string sourceDir, string name, string targetDir) { object wordFileName = sourceDir + name; //在此处放置用户代码以初始化页面 var word = new Word.ApplicationClass(); var wordType = word.GetType(); var docs = word.Documents; //打开文件 var docsType = docs.GetType(); var doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new[] { wordFileName, true, true }); //转换格式,另存为 var docType = doc.GetType(); var dotPlace = name.IndexOf(".", System.StringComparison.Ordinal); var strSaveFileName = targetDir + name.Substring(0, dotPlace) + ".html"; var saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); return saveFileName.ToString(); }
/// <summary> /// print Word /// </summary> /// <param name="wordfile">Fullpath and file name</param> /// <param name="printer">Printer name</param> public static void Print(string wordfile, string printer) { oWord.ApplicationClass word = new oWord.ApplicationClass(); Type wordType = word.GetType(); //Open WORD oWord.Documents docs = word.Documents; Type docsType = docs.GetType(); object objDocName = wordfile; oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, true, true }); doc.Application.ActivePrinter = printer; //Print to File //used doc.PrintOut() and Type.InvokeMember Type docType = doc.GetType(); object printFileName = wordfile + ".xps"; docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { false, false, oWord.WdPrintOutRange.wdPrintAllDocument, printFileName }); //Exit WORD wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); }
/// <summary> /// word转成html /// </summary> /// <param name="sourceDir"></param> /// <param name="name"></param> /// <param name="targetDir"></param> public static string WordToHtml(string sourceDir, string name, string targetDir) { object wordFileName = sourceDir + name; //在此处放置用户代码以初始化页面 var word = new Word.ApplicationClass(); var wordType = word.GetType(); var docs = word.Documents; //打开文件 var docsType = docs.GetType(); var doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new[] { wordFileName, true, true }); //转换格式,另存为 var docType = doc.GetType(); var dotPlace = name.IndexOf(".", System.StringComparison.Ordinal); object FileName = targetDir + name.Substring(0, dotPlace) + ".html"; object FileFormat = Word.WdSaveFormat.wdFormatFilteredHTML; //Word.WdSaveFormat.wdFormatWebArchive; object LockComments = false; object AddToRecentFiles = false; object ReadOnlyRecommended = false; object EmbedTrueTypeFonts = false; object SaveNativePictureFormat = true; object SaveFormsData = false; object SaveAsAOCELetter = false; object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8; object InsertLineBreaks = false; object AllowSubstitutions = false; object missing = System.Reflection.Missing.Value; object LineEnding = Word.WdLineEndingType.wdCRLF; object AddBiDiMarks = false; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new[] { FileName, FileFormat, LockComments, missing, AddToRecentFiles, missing, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); return FileName.ToString(); }
public void ToPdf() { bool occupy = true; System.Collections.Generic.List<string> strAry = new List<string>(); while (occupy) { try { using (File.Open(m_FilePathWord, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { } occupy = false;//如果可以运行至此那么就是 } catch (IOException e) { strAry.Add(e.ToString()); Thread.Sleep(100); } } WORD.ApplicationClass wordApp = new WORD.ApplicationClass(); WORD._Document wordDoc = null; object paramSourceDoc = m_FilePathWord; object paramMissing = Type.Missing; string strPdf = m_FilePathWord.Substring(0, m_FilePathWord.LastIndexOf('.')); string paramExportFilePath = strPdf; WORD.WdExportFormat paramexportFormat = WORD.WdExportFormat.wdExportFormatPDF; bool paramOpenAfterExport = false; WORD.WdExportOptimizeFor parameExportOptimizeFor = WORD.WdExportOptimizeFor.wdExportOptimizeForPrint; WORD.WdExportRange parameExportRange = WORD.WdExportRange.wdExportAllDocument; int paramStartPage = 0; int paramEndPage = 0; WORD.WdExportItem paramExportItem = WORD.WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; WORD.WdExportCreateBookmarks paramCreateBookMarks = WORD.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; try { wordDoc = wordApp.Documents.Open( ref paramSourceDoc, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing ); if (wordDoc != null) { wordDoc.ExportAsFixedFormat(paramExportFilePath, paramexportFormat, paramOpenAfterExport, parameExportOptimizeFor, parameExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookMarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); } if (wordDoc != null) { wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc); } if (wordApp != null) { wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); } PostHttpMsg pm = new PostHttpMsg(); pm.DataPost = strPdf + ".pdf"; pm.PostMsg(); } catch (System.Exception ex) { ex.ToString(); } finally { wordDoc = null; wordApp = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
/// <summary> /// 向doc文件写入数据 /// </summary> /// <param name="path"></param> /// <returns></returns> public bool WrithDocFile(string path) { string Quhua = string.Empty;//区划编码 string CheckType = string.Empty;//检查类型 try { //查看其行政区划编码 Quhua = path.Substring(path.IndexOf("(") + 1); Quhua = Quhua.Substring(0, Quhua.IndexOf(")")); } catch (Exception) { MessageBox.Show("不合法的文件夹格式"); return false; } if (path.Contains("GTSYQ")) CheckType = "国有土地使用权"; else if (path.Contains("JTSYQ")) CheckType = "集体土地使用权"; else CheckType = "集体土地所有权"; object file = path; //操作word文档 MSWord.Application wordApp; MSWord.Document wordDoc; wordApp = new MSWord.ApplicationClass(); Object nothing = Missing.Value; wordDoc = wordApp.Documents.Open(ref file, ref nothing, ref nothing, ref nothing); Bookmarks marks = wordDoc.Bookmarks; wordDoc.Bookmarks.get_Item("xzqdm").Range.Text = Quhua;//行政区代码 string quHuaName = new QuHuaHelper().GetQuHuaName(Quhua); wordDoc.Bookmarks.get_Item("rootpath1").Range.Text = quHuaName;//行政区划名称 wordDoc.Bookmarks.get_Item("startdate").Range.Text = DateTime.Now.ToShortDateString(); var sjwzx = from p in ComMsg.ResultShow where p.Gzlx.Equals("数据完整性") select p; wordDoc.Bookmarks.get_Item("sjwzxzqx").Range.Text = (from p in sjwzx where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//数据完整性_重缺陷 wordDoc.Bookmarks.get_Item("sjwzxqqx").Range.Text = (from p in sjwzx where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//数据完整性_轻缺陷 wordDoc.Bookmarks.get_Item("sjwzxtotal").Range.Text = sjwzx.ToList().Count.ToString();//数据完整性_错误合计 var jgfhx = from p in ComMsg.ResultShow where p.Gzlx.Equals("结构符合性") select p; wordDoc.Bookmarks.get_Item("jgfhxzqx").Range.Text = (from p in jgfhx where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//结构符合性_重缺陷 wordDoc.Bookmarks.get_Item("jgfhxqqx").Range.Text = (from p in jgfhx where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//结构符合性_轻缺陷 wordDoc.Bookmarks.get_Item("jgfhxtotal").Range.Text = jgfhx.ToList().Count.ToString();//结构符合性_错误合计 var jczb= from p in ComMsg.ResultShow where p.Gzlx.Equals("基础指标") select p; wordDoc.Bookmarks.get_Item("jczbzqx").Range.Text = (from p in jczb where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//基础指标_重缺陷 wordDoc.Bookmarks.get_Item("jczbqqx").Range.Text = (from p in jczb where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//基础指标_轻缺陷 wordDoc.Bookmarks.get_Item("jczbtotal").Range.Text = jczb.ToList().Count.ToString();//基础指标_错误合计 wordDoc.Bookmarks.get_Item("ljglzqx").Range.Text = "0";//逻辑关联_重缺陷 wordDoc.Bookmarks.get_Item("ljglqqx").Range.Text = "0";//逻辑关联_轻缺陷 wordDoc.Bookmarks.get_Item("ljgltotal").Range.Text = "0";//逻辑关联_错误合计 wordDoc.Bookmarks.get_Item("txjczqx").Range.Text = "0";//空间图形检查_重缺陷 wordDoc.Bookmarks.get_Item("txjcqqx").Range.Text = "0";//空间图形检查_轻缺陷 wordDoc.Bookmarks.get_Item("txjctotal").Range.Text = "0";//空间图形检查_错误合计 var hzbg=from p in ComMsg.ResultShow select p; wordDoc.Bookmarks.get_Item("hzbgjczqx").Range.Text = (from p in hzbg where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//汇总表格检查_重缺陷 wordDoc.Bookmarks.get_Item("hzbgjcqqx").Range.Text = (from p in hzbg where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//汇总表格检查_轻缺陷 wordDoc.Bookmarks.get_Item("hzbgjctotal").Range.Text = hzbg.ToList().Count.ToString();//汇总表格检查_错误合计 wordDoc.Bookmarks.get_Item("zqx1").Range.Text = (from p in hzbg where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//总计_重缺陷 wordDoc.Bookmarks.get_Item("qqx1").Range.Text = (from p in hzbg where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//总计_轻缺陷 wordDoc.Bookmarks.get_Item("total1").Range.Text =hzbg.ToList().Count.ToString();//总计_错误合计 wordDoc.Bookmarks.get_Item("zqx2").Range.Text = (from p in hzbg where p.Cwdj.Equals("重缺陷") select p).ToList().Count.ToString();//总计_重缺陷 wordDoc.Bookmarks.get_Item("qqx2").Range.Text = (from p in hzbg where p.Cwdj.Equals("轻缺陷") select p).ToList().Count.ToString();//总计_轻缺陷 wordDoc.Bookmarks.get_Item("total2").Range.Text = hzbg.ToList().Count.ToString();//总计_错误合计 wordDoc.Bookmarks.get_Item("sxsjtotal").Range.Text = hzbg.ToList().Count.ToString();//属性数据总和 wordDoc.Bookmarks.get_Item("slsjtotal").Range.Text = "0";//矢量数据总和 wordDoc.Bookmarks.get_Item("checkresult").Range.Text = quHuaName + "(" + Quhua + ")" + CheckType + "土地登记成果检查" + ((from p in hzbg where p.Cwdj.Equals("轻缺陷") select p).ToList().Count > 0 ? "未通过" : "通过"); wordDoc.Bookmarks.get_Item("rootpath2").Range.Text = quHuaName + "(" + Quhua + ")" + CheckType + "土地登记成果"; wordDoc.Bookmarks.get_Item("rootpath3").Range.Text = quHuaName + "(" + Quhua + ")" + CheckType + "土地登记成果"; object oMissing = System.Reflection.Missing.Value; wordDoc.SaveAs(ref file, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); wordDoc.Close(ref nothing, ref nothing, ref nothing); wordApp.Quit(ref nothing, ref nothing, ref nothing); return true; }
private void SignWordDocument(string documentPath, string signatureFile, bool openWord) { WORD.ApplicationClass WordApp = new WORD.ApplicationClass(); try { object _missing = System.Reflection.Missing.Value; object _docPath = documentPath; WORD.Document adoc = WordApp.Documents.Open(ref _docPath, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing); object unit = 6; object move = 0; int _endKey = WordApp.Selection.EndKey(ref unit, ref move); // int _endOfDoc = WordApp.Selection.End; WordApp.Selection.InlineShapes.AddPicture(signatureFile, ref _missing, ref _missing, ref _missing); WordApp.Visible = openWord; } catch (Exception ex) { string _s = ex.ToString(); } finally { WordApp = null; } }
private void createPDFVersion() { object oMissing = System.Reflection.Missing.Value; Word.ApplicationClass wordApp = new Word.ApplicationClass(); wordApp.Visible = false; Word.Document doc = null; try { SPFile workingField = CurrentFile; using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb web = site.OpenWeb(CurrentList.ParentWeb.ID)) { workingField = web.GetFile(CurrentFile.Url); } } Object filename = TEMP_PATH + workingField.Name; CCIUtility.LogInfo(filename.ToString(), "DEBUG"); //int size = 10 * 1024; //using (Stream stream = CurrentFile.OpenBinaryStream()) //{ // using (FileStream fs = new FileStream(filename.ToString(), FileMode.Create, FileAccess.Write)) // { // byte[] buffer = new byte[size]; // while (stream.Read(buffer, 0, buffer.Length) > 0) // { // fs.Write(buffer, 0, buffer.Length); // } // } //} Stream stream = workingField.OpenBinaryStream(); byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); var writer = File.OpenWrite(TEMP_PATH + workingField.Name); writer.Write(data, 0, data.Length); writer.Close(); object outputFileName; object fileFormat = Word.WdSaveFormat.wdFormatPDF; string ext = Path.GetExtension(workingField.Name); switch (ext) { case ".docx": outputFileName = TEMP_PATH + workingField.Name.Replace(".docx", ".pdf"); break; case ".dotx": outputFileName = TEMP_PATH + workingField.Name.Replace(".dotx", ".pdf"); break; default: outputFileName = TEMP_PATH + workingField.Name.Replace(".doc", ".pdf"); break; } if (ext == ".docx") { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename.ToString(), true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; if (mainPart.DocumentSettingsPart != null) { mainPart.DeletePart(mainPart.DocumentSettingsPart); } mainPart.Document.Save(); } } doc = wordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); addToPDFList(outputFileName); } catch (Exception ex) { CCIUtility.LogInfo(ex.Message, "Create PFD"); } finally { if (doc != null) { object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; ((Word._Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } if (wordApp != null) { ((Word._Application)wordApp).Quit(ref oMissing, ref oMissing, ref oMissing); wordApp = null; } try { if (File.Exists(TEMP_PATH + CurrentFile.Name)) { File.Delete(TEMP_PATH + CurrentFile.Name); } if (File.Exists(TEMP_PATH + Path.GetFileNameWithoutExtension(CurrentFile.Name) + ".pdf")) { File.Delete(TEMP_PATH + Path.GetFileNameWithoutExtension(CurrentFile.Name) + ".pdf"); } } catch (Exception) { CCIUtility.LogError("Couldn't delete generated pdf file", CCIappFeatureNames.CCIappInfrastructure); } } }
/** * Class constructor. It instantiates the Word application. */ public DocToXmlGenerator() { wordApplication = new Word.ApplicationClass(); wordApplication.Visible = false; }
public WordHelper(Word.ApplicationClass wordApplication) { _wordApplication = wordApplication; }
public static void Word2Pdf(string path, string savepath) { var word = new Word.ApplicationClass(); var wordType = word.GetType(); var docs = word.Documents; var docsType = docs.GetType(); var doc = (Word.Document)docsType.InvokeMember( "Open", BindingFlags.InvokeMethod, null, docs, new[] { (object)path, true, true }); var docType = doc.GetType(); docType.InvokeMember( "SaveAs", BindingFlags.InvokeMethod, null, doc, new[] { (object)savepath, Word.WdSaveFormat.wdFormatPDF }); docType.InvokeMember( "Close", BindingFlags.InvokeMethod, null, doc, new object[] { Word.WdSaveOptions.wdDoNotSaveChanges }); wordType.InvokeMember( "Quit", BindingFlags.InvokeMethod, null, word, null); }
private void button1_Click(object sender, EventArgs e) { string xmlDefinitionPath = @"E:\ibts.definition.xml"; string dataFilePath = @"E:\data.json"; dataDoc = getDocData(dataFilePath); definitionDTO = getDocDefinition(xmlDefinitionPath); XmlNode node = dataDoc.SelectSingleNode("/data/pagingDTO.check2"); XmlNode node2 = dataDoc.SelectSingleNode("/data/companyDTO/companyCode"); // return; object path; //文件路径变量 object destPath; //文件路径变量 MSWord.Application wordApp = null; //Word 应用程序变量 MSWord.Document wordDoc = null; //Word文档变量 path = @"E:\T22.docm"; //路径 destPath = @"E:\T25.docx"; //路径 //由于使用的是COM库,因此有许多变量需要用Missing.Value代替 Object Nothing = Missing.Value; try { wordApp = new MSWord.ApplicationClass(); //初始化 wordDoc = wordApp.Documents.Open(ref path, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); foreach (MSWord.InlineShape ishape in wordDoc.InlineShapes) { MSWord.Field f = ishape.Field; if (ishape.Type != MSWord.WdInlineShapeType.wdInlineShapeOLEControlObject) continue; String controlName = ishape.OLEFormat.Object.GetType().InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, ishape.OLEFormat.Object, null).ToString(); DocItemDefinitionDTO item = definitionDTO.getItem(controlName); if (item == null) continue; // 判断为 CheckBox if (f.Code.Text.Contains("Forms.CheckBox.1")) { Microsoft.Vbe.Interop.Forms.CheckBox control = (Microsoft.Vbe.Interop.Forms.CheckBox)ishape.OLEFormat.Object; setCheckBoxControl(item, control); } if (f.Code.Text.Contains("Forms.Label.1")) { Microsoft.Vbe.Interop.Forms.Label control = (Microsoft.Vbe.Interop.Forms.Label)ishape.OLEFormat.Object; setLabelControl(item, control); } else continue; } MSWord.ContentControls contentControls = wordDoc.ContentControls; foreach (MSWord.ContentControl control in contentControls) { String controlName = control.Tag; DocItemDefinitionDTO item = definitionDTO.getItem(controlName); if (item == null) continue; if (control.Type == MSWord.WdContentControlType.wdContentControlRichText) { setRichTextContentBoxControl(item, control); } } //WdSaveFormat 为Word 文档的保存格式 object format = MSWord.WdSaveFormat.wdFormatDocumentDefault; //将wordDoc文档对象的内容保存为DOC文档 wordDoc.SaveAs(ref destPath, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); MessageBox.Show("Success!"); } catch (Exception e1) { MessageBox.Show("Error:" + e1.Message); } finally { //关闭wordDoc文档对象 if (wordDoc != null) wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); //关闭wordApp组件对象 if (wordApp != null) wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); } }
/// <summary> /// catches Word's quit event /// normally it should not fire, but just to be shure /// safely release the internal Word Instance /// </summary> private void OnQuit() { wd=null; }
/// <summary> /// Preactivation /// It's usefull, if you need more speed in the main Program /// so you can preload Word. /// </summary> public void PreActivate() { if(wd == null) wd = new Microsoft.Office.Interop.Word.ApplicationClass(); }
/// <summary> /// Loads a document into the control /// </summary> /// <param name="t_filename">path to the file (every type word can handle)</param> public void LoadDocument(string t_filename) { deactivateevents = true; filename = t_filename; if(wd == null) wd = new Microsoft.Office.Interop.Word.ApplicationClass(); try { wd.CommandBars.AdaptiveMenus = false; wd.DocumentBeforeClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose); wd.ApplicationEvents4_Event_NewDocument += new Microsoft.Office.Interop.Word.ApplicationEvents4_NewDocumentEventHandler(OnNewDoc); wd.DocumentOpen+= new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc); wd.ApplicationEvents2_Event_Quit += new Microsoft.Office.Interop.Word.ApplicationEvents2_QuitEventHandler(OnQuit); } catch{} if(document != null) { try { object dummy=null; wd.Documents.Close(ref dummy, ref dummy, ref dummy); } catch{} } if( wordWnd==0 ) wordWnd = FindWindow( "Opusapp", null); if (wordWnd!=0) { SetParent( wordWnd, this.Handle.ToInt32()); object fileName = filename; object newTemplate = false; object docType = 0; object readOnly = true; object isVisible = true; object missing = System.Reflection.Missing.Value; try { if( wd == null ) { throw new WordInstanceException(); } if( wd.Documents == null ) { throw new DocumentInstanceException(); } if( wd != null && wd.Documents != null ) { document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible); } if(document == null) { throw new ValidDocumentException(); } } catch { } try { wd.ActiveWindow.DisplayRightRuler=false; wd.ActiveWindow.DisplayScreenTips=false; wd.ActiveWindow.DisplayVerticalRuler=false; wd.ActiveWindow.DisplayRightRuler=false; wd.ActiveWindow.ActivePane.DisplayRulers=false; wd.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdWebView; // .wdNormalView; } catch { } ///////////////////////////////////////////////////////// //int counter = wd.ActiveWindow.Application.CommandBars.Count; //for(int i = 0; i < counter;i++) //{ // try // { // wd.ActiveWindow.Application.CommandBars[i].Enabled=false; // } // catch // { // } //} ////////////////////////////////////////////////////////////// try { wd.Visible = true; wd.Activate(); SetWindowPos(wordWnd,this.Handle.ToInt32(),0,0,this.Bounds.Width+20,this.Bounds.Height+20, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME); MoveWindow(wordWnd,-5,-33,this.Bounds.Width+5,this.Bounds.Height+35,true); } catch { MessageBox.Show("Error: do not load the document into the control until the parent window is shown!"); } this.Parent.Focus(); } deactivateevents = false; }
private static bool ConvertWordToPdf(string fileIn, string fileOut) { ApplicationClass wordApplication = new ApplicationClass(); Document wordDocument = null; object paramSourceDocPath = fileIn; object paramMissing = Type.Missing; string paramExportFilePath = fileOut; const WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatPDF; const bool paramOpenAfterExport = false; const WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint; const WdExportRange paramExportRange = WdExportRange.wdExportAllDocument; const int paramStartPage = 0; const int paramEndPage = 0; const WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent; const bool paramIncludeDocProps = true; const bool paramKeepIrm = true; const WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks; const bool paramDocStructureTags = true; const bool paramBitmapMissingFonts = true; // ReSharper disable once InconsistentNaming const bool paramUseISO19005_1 = false; try { // Open the source document. wordDocument = wordApplication.Documents.Open( ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); //string tempFile = Path.Combine(Path.GetDirectoryName(fileOut), Path.GetFileName(fileIn)); //wordDocument.SaveAs(tempFile); //wordDocument.Close(); // Export it in the specified format. if (wordDocument != null) wordDocument.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIrm, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); } catch (Exception ex) { // Respond to the error Debug.WriteLine(ex.Message); return false; } finally { // Close and release the Document object. if (wordDocument != null) { wordDocument.Close(WdSaveOptions.wdDoNotSaveChanges, ref paramMissing, ref paramMissing); wordDocument = null; } // Quit Word and release the ApplicationClass object. if (wordApplication != null) { wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return true; }
/** * Extracts the xml content from the ms word document. */ private void extractXML(object doc, object xmlFile) { /* represents a single word document */ Word.Document wordDocument = null; // Opens the Microsoft Word application. this.openWordApplication(); try { // Open the Microsoft Word document. wordDocument = wordApplication.Documents.Open(ref doc, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform); } catch (Exception) { // An exception occurred. Maybe the MS Word is closed wordApplication = new Word.ApplicationClass(); wordApplication.Visible = false; // Open the Microsoft Word document. wordDocument = wordApplication.Documents.Open(ref doc, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform); } try { //Get xml data from Word document object filePath = (object)xmlFile; object format = Word.WdSaveFormat.wdFormatXML; wordDocument.SaveAs(ref filePath, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (Exception e) { // Closes the opened Word Document wordDocument.Close(ref falseObj, ref missing, ref missing); throw e; } // Closes the opened Word Document wordDocument.Close(ref falseObj, ref missing, ref missing); // Closes the Microsoft Word application. this.closeWordApplication(); }
public WordHelper() { _wordApplication = new Word.ApplicationClass(); }
/** * Opens the Microsoft Word application. */ private void openWordApplication() { this.wordApplication = new Word.ApplicationClass(); wordApplication.Visible = false; }
/** * Extracts the xml content from the ms word document. */ private string extractXML(object doc) { /* represents a single word document */ Word.Document wordDocument = null; string data = null; try { // Open the Microsoft Word document. wordDocument = wordApplication.Documents.Open(ref doc, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform); } catch (Exception) { // An exception occurred. Maybe the MS Word is closed wordApplication = new Word.ApplicationClass(); wordApplication.Visible = false; // Open the Microsoft Word document. wordDocument = wordApplication.Documents.Open(ref doc, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform); } try { //Get xml data from Word document data = wordDocument.Content.get_XML(true); } catch (Exception e) { // Closes the opened Word Document wordDocument.Close(ref falseObj, ref missing, ref missing); throw e; } // Closes the opened Word Document wordDocument.Close(ref falseObj, ref missing, ref missing); return data; }
static public void word2PdfFcih(object SourceFileName, object newFileName) { //Pid++; Microsoft.Office.Interop.Word.ApplicationClass MSdoc = null; //object Source = "d:\\Document" + Pid.ToString(System.Globalization.CultureInfo.CurrentCulture) + ".doc"; object Source = SourceFileName; object readOnly = false; object Unknown = System.Reflection.Missing.Value; //Type.Missing; object missing = Type.Missing; try { //Creating the instance of Word Application if (MSdoc == null) MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass(); MSdoc.Visible = false; MSdoc.Documents.Open(ref Source, ref Unknown, ref readOnly, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); MSdoc.Application.Visible = false; MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize; object FileName = newFileName; object FileFormat = WdSaveFormat.wdFormatPDF; object LockComments = false; object AddToRecentFiles = false; object ReadOnlyRecommended = false; object EmbedTrueTypeFonts = true; object SaveNativePictureFormat = false; object SaveFormsData = false; object SaveAsAOCELetter = false; //object Encoding = MsoEncoding.msoEncodingUSASCII; object InsertLineBreaks = false; object AllowSubstitutions = false; object LineEnding = WdLineEndingType.wdCRLF; object AddBiDiMarks = false; /* to get more details about SaveAs(...) function and it's parameter ,read this microsoft's link http://msdn2.microsoft.com/en-us/library/aa662158(office.10).aspx */ MSdoc.ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref missing, ref AddToRecentFiles, ref missing, ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat, ref SaveFormsData, ref SaveAsAOCELetter, ref /*Encoding*/missing, ref InsertLineBreaks, ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks); } catch (FileLoadException e) { Console.WriteLine(e.Message + "Error"); } catch (FileNotFoundException e) { Console.WriteLine(e.Message + "Error"); } catch (FormatException e) { Console.WriteLine(e.Message + "Error"); } finally { if (MSdoc != null) { MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown); //WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown); } // for closing the application // WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown); MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown); MSdoc = null; } }
private void gridControl1_DoubleClick(object sender, EventArgs e) { DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi = gridView1.CalcHitInfo((sender as System.Windows.Forms.Control).PointToClient(System.Windows.Forms.Control.MousePosition)); DataRow FocusRow; if (hi.RowHandle >= 0) { FocusRow = gridView1.GetDataRow(hi.RowHandle); string strType = FocusRow.ItemArray[3].ToString(); string strPath = FocusRow.ItemArray[4].ToString(); if (strType == "OUTLOOK") { try { Email.Application oApp = new Email.Application(); Email._MailItem oMailItem = (Email._MailItem)oApp.CreateItemFromTemplate(strPath, Type.Missing); //oMailItem.Subject = "abc"; oMailItem.Display(false); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else if (strType == "WORD") { try { Word.Application wordApp; Word.Document doc; wordApp = new Word.ApplicationClass(); wordApp.Visible = true; object fileName = strPath; object missing = Type.Missing; object fReadOnly = false; doc = wordApp.Documents.Open(ref fileName, ref missing, ref fReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); //doc.Activate(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else if (strType == "EXCEL") { try { Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); Excel.Workbook workBook = oExcel.Workbooks.Open(strPath, 0, true, 5, null, null, true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null); //Excel.Worksheet ws = (Excel.Worksheet)oExcel.ActiveSheet; //ws.Activate(); //ws.get_Range("A1", "IV65536").Font.Size = 8; oExcel.Visible = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } else if (strType == "PDF") { ACMS.ACMSStaff.To_Do_List.frmPDFviewer frm = new frmPDFviewer(strPath); frm.Show(); } else if (strType == "VIDEO") { frmVideoPlayer frmPlayer = new frmVideoPlayer(strPath); frmPlayer.Show(); } } else if (gridView1.FocusedRowHandle >= 0) { FocusRow = gridView1.GetDataRow(gridView1.FocusedRowHandle); string strType = FocusRow.ItemArray[3].ToString(); string strPath = FocusRow.ItemArray[4].ToString(); //ACMS.ACMSStaff.WorkFlow.MyCustomEditForm frm = new ACMS.ACMSStaff.WorkFlow.MyCustomEditForm((int)FocusRow.ItemArray[0], oUser.NDepartmentID()); //frm.Show(); } }
// ---------------------------------------------------------------------------------- private bool AddDigitalSignature(string _fileTempName, SPItemEventProperties properties) { object Visible = false; object readonlyfile = false; try { object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.ApplicationClass wordapp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document wordDocument = wordapp.Documents.Open(ref _fileTempName, ref missing, ref readonlyfile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing); SignatureSet _signatureSet = wordDocument.Signatures; Signature objSignature = _signatureSet.Add(); if (objSignature == null) { // DocumentNotSigned(properties); return false; } else { _signatureSet.Commit(); object saveChanges = true; wordDocument.Close(ref saveChanges, ref missing, ref missing); wordapp.Quit(ref missing, ref missing, ref missing); return true; } } catch { return false; } }
private static void ComputeStatistics() { int pagecount = 0; int wordcount = 0; object fileName = Filename; object readOnly = false; object isVisible = false; object objDNS = Word.WdSaveOptions.wdPromptToSaveChanges; object missing = System.Reflection.Missing.Value; Word._Application WordApp = new Word.ApplicationClass(); Word._Document aDoc = null; try { aDoc = WordApp.Documents.Open ( ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing ); Word.WdStatistic pagestat = Word.WdStatistic.wdStatisticPages; Word.WdStatistic wordstat = Word.WdStatistic.wdStatisticWords; pagecount = aDoc.ComputeStatistics(pagestat, ref missing); wordcount = aDoc.ComputeStatistics(wordstat, ref missing); } catch (Exception ex) { } finally { if (aDoc != null) { aDoc.Close(ref objDNS, ref missing, ref missing); Marshal.ReleaseComObject(aDoc); aDoc = null; } if (WordApp != null) { WordApp.Quit(ref objDNS, ref missing, ref missing); Marshal.ReleaseComObject(WordApp); WordApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); } TotalPages = pagecount; NoOfWords = wordcount; }