private void Clean() { if (oDoc != null) { oDoc.Close(ref oFalse, ref missing, ref missing); } oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing); }
public void Dispose() { if (m_Document != null) { m_Document.Close(); } if (m_WordApplication != null) { m_WordApplication.Quit(); } }
///<summary>Forces a document to close.</summary> ///<remarks>This method works around Office issues.</remarks> public static void CloseDoc(this _Document doc) { try { doc.Close(ref dontSave, ref Missing, ref Missing); doc.Close(ref Missing, ref Missing, ref Missing); } catch (COMException) { try { doc.Close(ref dontSave, ref Missing, ref Missing); doc.Close(ref dontSave, ref Missing, ref Missing); } catch (COMException) { } } }
/// <summary> /// 动态生成Word文档并填充内容 /// </summary> /// <param name="dir">文档目录</param> /// <param name="fileName">文档名</param> /// <returns>返回自定义信息</returns> public static bool CreateWordFile(string dir, string fileName) { try { Object oMissing = System.Reflection.Missing.Value; if (!Directory.Exists(dir)) { //创建文件所在目录 Directory.CreateDirectory(dir); } //创建Word文档(Microsoft.Office.Interop.Word) _Application WordApp = new Application(); //WordApp.Visible = true; _Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing); //保存 object filename = dir + fileName; WordDoc.SaveAs(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); WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); return(true); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return(false); } }
public static void RemoveCitations(string f_name) { _Application word_app = new Application(); word_app.Visible = false; object missing = Type.Missing; object filename = f_name; object confirm_conversions = false; object read_only = false; object add_to_recent_files = false; object format = 0; _Document word_doc = word_app.Documents.Open(ref filename, ref confirm_conversions, ref read_only, ref add_to_recent_files, ref missing, ref missing, ref missing, ref missing, ref missing, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object index = 1; while (word_doc.Hyperlinks.Count > 0) { word_doc.Hyperlinks.get_Item(ref index).Delete(); } object save_changes = true; word_doc.Close(ref save_changes, ref missing, ref missing); word_app.Quit(ref save_changes, ref missing, ref missing); Console.WriteLine("Done"); }
//保存文件 public static bool SaveFile(string filePath, MyNode myNode) { try { //初始化 object fileobj = filePath; object unknow = System.Reflection.Missing.Value; //打开word程序,创建一个新的word文档,但是还没有保存到硬盘中 ApplicationClass wordApp = new ApplicationClass(); _Document doc = wordApp.Documents.Add(ref unknow, ref unknow, ref unknow, ref unknow); //这里开始写文件 //深度优先遍历 //saveNode(doc, myNode,1); //保存word文档 doc.SaveAs(ref fileobj, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow); doc.Close(ref unknow, ref unknow, ref unknow); wordApp.Documents.Save(ref unknow, ref unknow); wordApp.Quit(ref unknow, ref unknow, ref unknow); return(true); } catch (Exception e) { return(false); } }
//保存新文件 public void SaveDocument(string filePath) { object fileName = filePath; object format = WdSaveFormat.wdFormatDocument;//保存格式 object miss = System.Reflection.Missing.Value; while (true) { try { wordDoc.SaveAs(ref fileName, ref format, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); break; } catch (COMException ex) { if (System.Windows.Forms.MessageBox.Show("发生错误,错误码为:" + ex.ErrorCode.ToString() + "\r\n请检查" + fileName + "是否已经打开\r\n是否重试", "发生错误", System.Windows.Forms.MessageBoxButtons.RetryCancel) == System.Windows.Forms.DialogResult.Cancel) { break; } } } //关闭wordDoc,wordApp对象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); }
public void EditClick(RichTextBox docBox) { docBox.Document.Blocks.Clear(); OpenFileDialog ofd = new OpenFileDialog //Выбор файла для редактирования { Filter = "Word files (*.docx)|*.docx|All files (*.*)|*.*", InitialDirectory = Path.Combine( Path.GetDirectoryName(Environment.GetCommandLineArgs()[0])) }; if (ofd.ShowDialog() == true) { Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application(); object File = ofd.FileName; object nullobject = System.Reflection.Missing.Value; wordObject.DisplayAlerts = WdAlertLevel.wdAlertsNone; _Document docs = wordObject.Documents.Open(ref File, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject); docs.ActiveWindow.Selection.WholeStory(); docs.ActiveWindow.Selection.Copy(); docBox.Paste(); docs.Close(ref nullobject, ref nullobject, ref nullobject); wordObject.Quit(); } else { MessageBox.Show("Отмена редактирования"); } }
/// <summary> /// Печать акта приёмки заказа /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPrint_Click(object sender, EventArgs e) { var templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "акт выдачи оборудования.dotx"); if (!File.Exists(templateFile)) { throw new Exception("Не найден файл " + templateFile); } var oWord = new Word.Application(); _Document oDoc = null; var newTemplateFile = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, $"Акты выдачи\\акт_выдачи_оборудования_{DateTime.Now:dd.MM.yyyy_HH.mm.ss}_{this.textBoxFIO.Text}.docx"); try { oDoc = oWord.Documents.Add(templateFile); this.SetTemplate(oDoc); oDoc.SaveAs2(FileName: newTemplateFile); } finally { oDoc?.Close(); oWord.Quit(); } MessageBox.Show("Сохранение прошло успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); Process.Start(newTemplateFile); }
private void CreateWordDocument() { _Document oDoc = null; try { Word._Application oWord = new Word.Application(); string source = @"C:\Users\temch\Desktop\Шаблон.dotx"; oDoc = oWord.Documents.Add(source); Word.Bookmarks wBookmarks = oDoc.Bookmarks; Word.Range wRange; string[] arr = { "27", "Tema", "Shevchenko" }; int i = 0; foreach (Word.Bookmark mark in wBookmarks) { wRange = mark.Range; wRange.Text = arr[i]; i++; } string pathToSaveObj = @"C:\Users\temch\Desktop\Контракт.docx"; oDoc.SaveAs2(pathToSaveObj); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { oDoc.Close(); oDoc = null; } }
public void CreateDocument(string docFilePath, Image image) { _Application oWord = new Microsoft.Office.Interop.Word.Application(); //Nếu tạo một Document _Document oDoc = oWord.Documents.Add(); //Nếu mở một Document //Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Open(docFilePath, ReadOnly: false, Visible: true); //Để xem điều gì đang xảy ra trong khi điền tập tài liệu từ Visible = true oWord.Visible = true; //Chèn ảnh từ mảng byte vào MS Word, sử dụng Clipboard để dán Image vào tài liệu Object oMissing = System.Reflection.Missing.Value; Clipboard.SetDataObject(image); var oPara = oDoc.Content.Paragraphs.Add(ref oMissing); oPara.Range.Paste(); oPara.Range.InsertParagraphAfter(); //Nếu tạo document oDoc.SaveAs(docFilePath); //Nếu mở một document //oDoc.Save(); oDoc.Close(); oWord.Quit(); }
//保存新文件 public void SaveDocument(string filePath) { object fileName = filePath; object format = WdSaveFormat.wdFormatDocument;//保存格式 //object miss =System.Reflection.Missing.Value; try { wordDoc.SaveAs(ref fileName, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); } catch (System.Exception ex) { //MessageBox.Show(ex.Message); } //关闭wordDoc,wordApp对象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); }
public static bool WordToHtml(string wordFileName, string htmlFileName) { try { Object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word._Application WordApp = new Microsoft.Office.Interop.Word.Application(); WordApp.Visible = false; object filename = wordFileName; _Document 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); // Type wordType = WordApp.GetType(); // 打开文件 Type docsType = WordApp.Documents.GetType(); // 转换格式,另存为 Type docType = WordDoc.GetType(); object saveFileName = htmlFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML }); //保存 WordDoc.Save(); WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); return(true); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return(false); } }
public bool ConvertToPdf(String docFolder, String docFile, String pdfFolder, String pdfFile) { WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF; bool result; object paramMissing = Type.Missing; try { object paramSourceDocPath = docFolder + "/" + docFile; string paramExportFilePath = pdfFolder + "/" + pdfFile; WdExportFormat paramExportFormat = exportFormat; bool paramOpenAfterExport = false; WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint; WdExportRange paramExportRange = WdExportRange.wdExportAllDocument; int paramStartPage = 0; int paramEndPage = 0; WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; _wordDoc = _wordApp.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); if (_wordDoc != null) _wordDoc.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); result = true; } catch (Exception) { return false; } finally { _wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing); _wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing); GC.Collect(); GC.WaitForPendingFinalizers(); } return result; }
//保存新文件 public void SaveDocument(string filePath) { object fileName = filePath; object format = WdSaveFormat.wdFormatDocument;//保存格式 object miss = System.Reflection.Missing.Value; wordDoc.SaveAs(ref fileName, ref format, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); //关闭wordDocwordApp对象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); }
void button1_Click(object sender, EventArgs e) { //var application = new Microsoft.Office.Interop.Word.Application(); //var document = new Microsoft.Office.Interop.Word.Document(); _Document oDoc = GetDoc(@"D:\Проект работы с шаблонами\NEW_C_PRJ\test.docx"); oDoc.SaveAs2(FileName: @"D:\Проект работы с шаблонами\NEW_C_PRJ\test_2.docx"); oDoc.Close(); }
public Word._Application oWord = new Word.Application(); // создаем документ Ворд public void OpenSaveDocMethod(string pathopen, string pathsave, MyDelegateWord temp) { // Берем шаблон присваиваем закладкам параметры и сохраняем его _Document oDoc = oWord.Documents.Add(Environment.CurrentDirectory + pathopen); temp.DynamicInvoke(oDoc); oDoc.SaveAs(Environment.CurrentDirectory + pathsave); oDoc.Close(); }
// 保存新文件 public void SaveDocument(string filePath) { wordApp.Visible = false; //不可见直接保存 wordDoc.SaveAs(filePath); //保存 wordDoc.Close(true); //关闭 wordApp.Quit(); //释放Word进程 }
public void ChangeToPDF(object WordPath, string PDFPath) { Console.WriteLine("开始将Word转成PDF"); _Document doc = wordApp.Documents.Open(ref WordPath, ref Nothing); doc.ExportAsFixedFormat(PDFPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 1, 1, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, true, false); object NotSave = WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref NotSave, ref Nothing, ref Nothing); }
private void CloseWord() { if (application != null) { document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; } }
//Freeing up resources allocated by Word and Doc etc.. private void CloseCOMObject(bool quit) { if (quit) { WrdDocObj.Close(true, null, null); WrdAppObj.Quit(); } releaseObject(WrdDocObj); WrdDocObj = null; releaseObject(WrdAppObj); WrdAppObj = null; }
public void Close(bool isSaveChanges) { object saveChanges = WdSaveOptions.wdDoNotSaveChanges; if (isSaveChanges) { saveChanges = WdSaveOptions.wdSaveChanges; } if (m_Document != null) { m_Document.Close(ref saveChanges, ref missing, ref missing); } }
public void Close(_Document doc) { object missingValue = Type.Missing; object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; if (doc != null) { doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue); } if (this.wordApp != null) { this.wordApp.Quit(ref oMissing, ref oMissing, ref oMissing); } }
public Threading.Task PrintAsync(ViewClaim claim, string selectedPrinter) { if (claim == null) { throw new ArgumentNullException("claim"); } Threading.Task tsk = Threading.Task.Run(async() => { _jobId++; lock (_locker) //Write to thread shared variable; { _backgroundJobs.Enqueue(_jobId); } Documents docs = null; _Document doc = null; try { docs = _wordApplication.Documents; doc = docs.Add(_wordTemplatePath); var d = FieldMapping(claim); FillFields(doc.Fields, d); //doc.Activate(); //_wordApplication.Dialogs[WdWordDialog.wdDialogFilePrint].Show(); //if (result == -1) //{ // doc.PrintOut(); //} //Don't call microsoft word PrintOut method directly here because PrintOut method //Runs async and will return immediately, therefor letting you to close the word befor //The print job finished which will lead to uncompleted printing job. //So, the solution is to wrap the Word 'PrintOut' method in an asyn method and then //wait on it so we will not proceed until my async method return which will return only //after the Word PrintOut method runs to complete. await PrintOut(doc, selectedPrinter); } finally { doc.Close(false); lock (_locker) //Write to thread shared variable; { _backgroundJobs.Dequeue(); } } } ); return(tsk); }
public void Print(string filepathandname) { WdSaveFormat format = WdSaveFormat.wdFormatPDF; // Create an instance of Word.exe _Application oWord = new Application { // Make this instance of word invisible (Can still see it in the taskmgr). Visible = false }; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = true; // Does not cause any word dialog to show up //object readOnly = false; // Causes a word object dialog to show at the end of the conversion object oInput = filepathandname; object oOutput = filepathandname.Substring(0, filepathandname.Length - 4) + "pdf"; object oFormat = format; object oPrintToFile = true; // Load a document into our instance of word.exe _Document oDoc = oWord.Documents.Open( ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Make this document the active document. oDoc.Activate(); // Save this document using Word //oDoc.SaveAs(ref oOutput, ref oFormat, 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 // ); oWord.Visible = false; PrintDialog pDialog = new PrintDialog(); oWord.ActivePrinter = GlobalVariables.PDF_PRINTER; oDoc.PrintOut(ref oMissing, ref oMissing, ref oMissing, ref oOutput, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oPrintToFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Close(SaveChanges: false); oDoc = null; }
public static void saveFile() { try { oDoc.SaveAs(path + filename); oDoc.Close(); oWord.Quit(); //realease from memory and call the GC releaseObject(oDoc); releaseObject(oWord); }catch (Exception e) { Console.WriteLine("Error saving the Word Doc: " + filename); } }
/// <summary> /// Método que fecha a planilha de dados do Excel e, salva ou não /// a planilha de dados. /// </summary> /// <param name="MostrarExcel"><Valor booleano, onde, 'true' salva a planilha de dados./param> public void FecharWord(Boolean SalvarArq) { try { mDoc.Close(true, "", ""); } catch { } try { mWord.Documents.Close(); //mWord.Quit(); Marshal.ReleaseComObject(mWord); } catch { } }
/// <summary> /// Método responsável por criar um novo documento do Word (DOCX ou DOC). /// </summary> /// <param name="CaminhoArq">String contendo o caminho + nome + extensão do documento</param> /// <param name="FecharWordAoCriar">Valor booleando, onde, 'true' encerra os objetos instanciados</param> /// <param name="MostrarWord"><Valor booleano, onde, 'true' mostra o documento/param> public void CriaWord(String CaminhoArq, Boolean FecharWordAoCriar, Boolean MostrarWord) { if (mWord == null) { throw new NotImplementedException("Word não está propriamente instalado"); } if (String.IsNullOrEmpty(CaminhoArq)) { throw new NotImplementedException("Caminho do arquivo não existe"); } if (System.IO.File.Exists(CaminhoArq)) { throw new System.IO.FileLoadException(String.Format("O arquivo informado '{0}' já existe e não pode ser substituído", CaminhoArq)); } if (!CaminhoArq.ToUpper().StartsWith("\\") && !CaminhoArq.ToUpper().StartsWith("C") && !CaminhoArq.ToUpper().EndsWith(".DOCX") && !CaminhoArq.ToUpper().EndsWith(".DOC")) { throw new ArgumentOutOfRangeException("Caminho informado não está no formato correto (não é unidade de rede nem unidade local ou não possuí a extensão 'DOCX' ou 'DOC'"); } object misValue = System.Reflection.Missing.Value; //Precisei adicionar essa condição pois estava sempre mostrando o Word (I don't know why!!) mWord.Visible = MostrarWord; mDoc = mWord.Documents.Add(ref misValue, ref misValue, ref misValue, ref misValue); mDoc.SaveAs2(CaminhoArq); if (FecharWordAoCriar) { mDoc.Close(true, misValue, misValue); //mWord.Quit(ref misValue, ref misValue, ref misValue); Marshal.ReleaseComObject(mWord); Marshal.ReleaseComObject(mDoc); } _CaminhoArqWord = CaminhoArq.ToUpper(); _MostrarWord = MostrarWord; if (_MostrarWord) { AbrirWord(); } }
public static void ReplaceMailMergeFields(string dir, string msWordFileName, IMergeFieldsProvider domainObject, string fileSuffix) { object docName = msWordFileName; object missing = Missing.Value; // Hide MS Word's window. var app = new Application { Visible = false } as _Application; var path = dir + docName as object; _Document doc = app.Documents.Open(ref path); MailMerge mailMerge = doc.MailMerge; // Try to find the field name. foreach (MailMergeField f in mailMerge.Fields) { // Assuming the field code is: MERGEFIELD "mailMergeFieldName" string mailMergeFieldName = f.Code.Text; string newValue = domainObject.GetContentsFor(mailMergeFieldName); if (!string.IsNullOrWhiteSpace(newValue)) { f.Select(); // Replace selected field with supplied value. app.Selection.TypeText(newValue); } } // Save changes and close MS Word. object newName = dir + msWordFileName.Replace(".docx", "") + "-" + fileSuffix + ".docx"; doc.SaveAs2(ref newName); object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref saveChanges, ref missing, ref missing); app.Quit(ref missing, ref missing, ref missing); }
public void MergeFieldsInWordDoc(string sourcePath, IDocumentMergeFieldsProvider sourceObject, string destinationPath) { object missing = Missing.Value; // Hide MS Word's window. Application app = new Application { Visible = false }; var path = sourcePath as object; _Document doc = app.Documents.Open(ref path); MailMerge mailMerge = doc.MailMerge; foreach (MailMergeField f in mailMerge.Fields) { // Assuming the field code is: MERGEFIELD "mailMergeFieldName" string fieldName = f.Code.Text; string newValue = GetValueForMergeField(sourceObject, fieldName); if (!string.IsNullOrWhiteSpace(newValue)) { f.Select(); // Replace selected field with supplied value. app.Selection.TypeText(newValue); } } // Save changes and close MS Word. object newName = destinationPath as object; doc.SaveAs2(ref newName); object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref saveChanges, ref missing, ref missing); //TODO: Fix - check with Stef //app.Quit(ref missing, ref missing, ref missing); }
// Вывод текста в ворд файл private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e) { if (label27.Text != "") { oWord = new Word.Application(); // Считывает шаблон и сохраняет измененный в новом _Document oDoc = GetDoc(Environment.CurrentDirectory + "\\pattern.docx"); oDoc.SaveAs(FileName: Environment.CurrentDirectory + "\\РЕЦЕНЗИЯ.docx"); string Filename = @"РЕЦЕНЗИЯ.docx"; Process.Start(Filename); oDoc.Close(); } else { MessageBox.Show("Чтобы «Сохранить WORD» необходимо сформировать очет - Ctr+G", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void InputWord(string url) { Random rd = new Random(); int rdd = rd.Next(10, 100); string filename = "rs"+DateTime.Now.ToString("yyyy-MM-dd") + rdd.ToString() + ".doc"; string LocalPath = null; //string pdfurl=null; try { int poseuqlurl = url.IndexOf('='); int possnap; string url1; string pdfname; url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1); possnap = url1.LastIndexOf('/'); pdfname = url1.Substring(possnap + 1, url1.Length - possnap - 1); filename = pdfname; /*int poseuqlurl = url.IndexOf('='); string url1; url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1); //pdfurl;*/ Uri u = new Uri(url1); //Uri u = new Uri(url); //filename = "123.doc"; //string time1 = DateTime.Now.ToString(); //filename = DateTime.Now.ToString() + ".doc"; LocalPath = "D:\\files\\" + filename; if (!File.Exists(@LocalPath)) { //不存在 HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u); mRequest.Method = "GET"; mRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse(); Stream sIn = wr.GetResponseStream(); FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write); byte[] bytes = new byte[4096]; int start = 0; int length; while ((length = sIn.Read(bytes, 0, 4096)) > 0) { fs.Write(bytes, 0, length); start += length; } sIn.Close(); wr.Close(); fs.Close(); string pdfpath = showwordfiles(LocalPath); } } catch { } //LocalPath = "D:\\1111.doc"; delet_tables(LocalPath); FileInfo fi = new FileInfo(LocalPath); fi.Attributes = FileAttributes.ReadOnly; //然后完成对文档的解析 _Application app = new Microsoft.Office.Interop.Word.Application(); _Application app1 = new Microsoft.Office.Interop.Word.Application(); _Application app2 = new Microsoft.Office.Interop.Word.Application(); _Application app3 = new Microsoft.Office.Interop.Word.Application(); _Application app4 = new Microsoft.Office.Interop.Word.Application(); _Application app5 = new Microsoft.Office.Interop.Word.Application(); _Application app6 = new Microsoft.Office.Interop.Word.Application(); _Application app7 = new Microsoft.Office.Interop.Word.Application(); //_Document doc; //string temp; //type1 = "SyRS"; //type2 = "TSP"; //string pattern1 = @"...-SyRS-...."; //pattern1 = @"^\[\w+-\w+-\w+-\d+\]"; //pattern2 = @"\[\w+-\w+-\d+\]"; pattern1 = @"^\[\w{3,}-.+\]"; pattern2 = @"\[\w{3,}-.+?\]"; /*pattern1 = @"^\[\w+-\w+-\d+\]"; pattern2 = @"\[\w+-\w+-\d+\]";*/ pattern3 = @"End"; pattern4 = @"^#"; //string pattern5 = @"[*]"; //object fileName = @"D:\\projectfiles\cascofiles\testdoc.doc" //E:\\cascofiles\testdoc.doc object fileName = LocalPath; // if (dlg.ShowDialog() == DialogResult.OK) // { // fileName = dlg.FileName; // } object unknow = System.Type.Missing; //object unknow1 = System.Reflection.Missing.Value; doc = app.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc1 = app1.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc2 = app2.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc3 = app3.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc4 = app4.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc5 = app5.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc6 = app6.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc doc7 = app7.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc pcount = doc.Paragraphs.Count;//count the paragraphs int jjj = pcount; //Thread t1 = new Thread(new ThreadStart(thread1)); //Thread t2 = new Thread(new ThreadStart(thread2)); var t1 = new System.Threading.Tasks.Task(() => thread1()); var t2 = new System.Threading.Tasks.Task(() => thread2()); var t3 = new System.Threading.Tasks.Task(() => thread3()); var t4 = new System.Threading.Tasks.Task(() => thread4()); var t5 = new System.Threading.Tasks.Task(() => thread5()); var t6 = new System.Threading.Tasks.Task(() => thread6()); var t7 = new System.Threading.Tasks.Task(() => thread7()); var t8 = new System.Threading.Tasks.Task(() => thread8()); t1.Start(); t2.Start(); t3.Start(); t4.Start(); t5.Start(); t6.Start(); t7.Start(); t8.Start(); System.Threading.Tasks.Task.WaitAll(t1,t2,t3,t4,t5,t6,t7,t8); doc.Close(ref unknow, ref unknow, ref unknow); doc1.Close(ref unknow, ref unknow, ref unknow); doc2.Close(ref unknow, ref unknow, ref unknow); doc3.Close(ref unknow, ref unknow, ref unknow); doc4.Close(ref unknow, ref unknow, ref unknow); doc5.Close(ref unknow, ref unknow, ref unknow); doc6.Close(ref unknow, ref unknow, ref unknow); doc7.Close(ref unknow, ref unknow, ref unknow); app.Quit(ref unknow, ref unknow, ref unknow); app1.Quit(ref unknow, ref unknow, ref unknow); app2.Quit(ref unknow, ref unknow, ref unknow); app3.Quit(ref unknow, ref unknow, ref unknow); app4.Quit(ref unknow, ref unknow, ref unknow); app5.Quit(ref unknow, ref unknow, ref unknow); app6.Quit(ref unknow, ref unknow, ref unknow); app7.Quit(ref unknow, ref unknow, ref unknow); //string jsonString = string1+string2+string3+string4+string5+string6+string7+string8; var json = new JavaScriptSerializer().Serialize(aaa.finalstrings); //jsonString = string1; //return myarray[0].arraycontent[5]; Context.Response.ContentType = "text/json"; Context.Response.Write(json); Context.Response.End(); //return jsonString; //return myarray[0].sourse[0]; //return "123"; }
/// <summary> /// 转为PDF /// </summary> /// <param name="dstDir"></param> /// <param name="docFileName"></param> /// <returns></returns> public Boolean ConvertToPDF(String dstDir, String docFileName) { string wjm = Path.GetFileNameWithoutExtension(docFileName); string path = FormatPath(wjm); //该目录存在 dstDir += path; string pdfFile = dstDir + wjm + ".pdf"; string docFile = dstDir + docFileName; WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF; bool result; object paramMissing = Type.Missing; //ApplicationClass wordApplication = new ApplicationClass(); this._wordApp = new ApplicationClass(); try { object paramSourceDocPath = docFile; string paramExportFilePath = pdfFile; WdExportFormat paramExportFormat = exportFormat; bool paramOpenAfterExport = false; WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint; WdExportRange paramExportRange = WdExportRange.wdExportAllDocument; int paramStartPage = 0; int paramEndPage = 0; WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; _wordDoc = _wordApp.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); if (_wordDoc != null) _wordDoc.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); result = true; } catch (Exception) { return false; } finally { _wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing); _wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing); GC.Collect(); GC.WaitForPendingFinalizers(); } return result; }
private void CloseDocument(_Document document) { object saveChanges = WdSaveOptions.wdDoNotSaveChanges; object missing = System.Reflection.Missing.Value; document.Close(ref saveChanges, ref missing, ref missing); Application.Quit(ref saveChanges, ref missing, ref missing); }