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); }
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(); }
/// <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); } }
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; }
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); }
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); }
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); } }
/// <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); } }
/// <summary> /// Close the current Document in the control --> you can /// load a new one with LoadDocument /// </summary> public void CloseControl() { /* * this code is to reopen Word. */ try { deactivateevents = true; object dummy = null; object dummy2 = (object)false; try { if (document != null) { document.Close(ref dummy, ref dummy, ref dummy); } } catch (Exception e) { } // Change the line below. try { if (wd != null) { wd.Quit(ref dummy2, ref dummy, ref dummy); } } catch (Exception e) { } deactivateevents = false; } catch (Exception ex) { String strErr = ex.Message; } }
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); } }
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; }
//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); }
public override void Dispose() { _wordDocument.Close(false); Marshal.ReleaseComObject(_wordDocument); _application.Quit(false); Marshal.ReleaseComObject(_application); }
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 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; }
protected static string SingleDoc(Word.ApplicationClass application, Word.Document Doc, string newFilePath) { try { SavePDF sv = new SavePDF(); bool finish = sv.Save(Doc, newFilePath); } catch (Exception ex) { Doc.Close(); application.Quit(); Console.WriteLine("Save PDF Failed With: " + ex.ToString()); Console.WriteLine("Press Enter To Continue/Exit"); Console.ReadLine(); } Doc.Close(); application.Quit(); return("Save PDF Finished Successfully"); }
/// <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); }
public static void WriteWord(string file_doc, string dir_pic) { #region 生成Word //实例化一个Document对象 Document doc = new Document(); //添加section和段落 Section section = doc.AddSection(); Paragraph para = section.AddParagraph(); DirectoryInfo info = new DirectoryInfo(dir_pic); var f = info.GetFiles(); var pics = (from x in f orderby int.Parse(x.Name.Substring(0, x.Name.Length - 4)) select x.FullName).ToList();//不然11.jpg在2.jpg前面 for (int i = 0; i < pics.Count; i++) { Image image = Image.FromFile(pics[i]); DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(image); image.Dispose(); picture.TextWrappingStyle = TextWrappingStyle.Inline;//设置文字环绕方式 doc.Sections[0].Paragraphs[0].AppendText(Environment.NewLine); } doc.SaveToFile(file_doc, FileFormat.Docx2013);//保存到文档 #endregion #region 去水印 object path = file_doc; Object Nothing = Missing.Value; Word.Application wordApp = new Word.ApplicationClass { Visible = false //使文档不可见 }; //初始化 object unite = Word.WdUnits.wdStory; Word.Document wordDoc = wordApp.Documents.Open(file_doc, Type.Missing, false); wordApp.Selection.Find.Replacement.ClearFormatting(); wordApp.Selection.Find.ClearFormatting(); wordApp.Selection.Find.Text = "Evaluation Warning: The document was created with Spire.Doc for .NET."; //需要被替换的文本 wordApp.Selection.Find.Replacement.Text = ""; //替换文本 object oMissing = Missing.Value; object replace = Word.WdReplace.wdReplaceAll; //执行替换操作 wordApp.Selection.Find.Execute( ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing); object format = Word.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); //关闭wordApp组件对象 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); #endregion }
/// <summary> /// Stops Word /// </summary> private void StopWord() { if (IsWordRunning) { Logger.WriteToLog("Stopping Word"); try { _word.Quit(false); } catch (Exception exception) { Logger.WriteToLog($"Word did not shutdown gracefully, exception: {ExceptionHelpers.GetInnerException(exception)}"); } var counter = 0; // Give Word 2 seconds to close while (counter < 200) { if (!IsWordRunning) { break; } counter++; Thread.Sleep(10); } if (IsWordRunning) { Logger.WriteToLog($"Word did not shutdown gracefully in 2 seconds ... killing it on process id {_wordProcess.Id}"); _wordProcess.Kill(); Logger.WriteToLog("Word process killed"); } else { Logger.WriteToLog("Word stopped"); } } if (_word != null) { Marshal.ReleaseComObject(_word); _word = null; } _wordProcess = null; GC.Collect(); GC.WaitForPendingFinalizers(); }
public void SerachTextTest() { 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\Solution Design Documnets\Letter Generation Automation Tool User Requirements v1.0.docx", false); doc.Activate(); object unite = WdUnits.wdStory; // app.Selection.EndKey(ref unite, Type.Missing); //将光标移动到文档末尾 app.Selection.WholeStory(); app.Selection.Find.Forward = true; app.Selection.Find.ClearFormatting(); app.Selection.Find.MatchWholeWord = true; app.Selection.Find.MatchCase = false; app.Selection.Find.Wrap = WdFindWrap.wdFindContinue; bool isFind = app.Selection.Find.Execute("Log文件夹"); int start = app.Selection.Range.Start; int end = app.Selection.Range.End; int length = app.Selection.Range.StoryLength; Microsoft.Office.Interop.Word.Range range = app.Selection.Range; object p = range.Information[WdInformation.wdActiveEndPageNumber]; range.SetRange(end - 1, app.ActiveDocument.Content.End); int MoveStartWhileCount = range.MoveStartUntil("\r", WdConstants.wdBackward); int getStart = range.Start; int getEnd = range.End; range.Select(); int paragraphsCount = range.Paragraphs.Count; range.Find.Forward = true; range.Find.ClearFormatting(); range.Find.MatchWholeWord = true; range.Find.MatchCase = false; range.Find.Wrap = WdFindWrap.wdFindContinue; bool isFind2 = app.Selection.Range.Find.Execute("Log文件夹"); //doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, Type.Missing, Type.Missing, true); doc.Save(); doc.Close(); app.Quit(); }
static void word2pdf(string sourcePath, string targetPath) { // Console.WriteLine("hello.."); Word.Application myWordApp; Word.Document myWordDoc; myWordApp = new Word.ApplicationClass(); // object filepath = fileString; object filepath = sourcePath; object oMissing = System.Reflection.Missing.Value; myWordDoc = myWordApp.Documents.Open(ref filepath, 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); Word.WdExportFormat paramExportFormat = Word.WdExportFormat.wdExportFormatPDF; bool paramOpenAfterExport = false; Word.WdExportOptimizeFor paramExportOptimizeFor = // Word.WdExportOptimizeFor.wdExportOptimizeForPrint; Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen; Word.WdExportRange paramExportRange = 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; string paramExportFilePath = targetPath; myWordDoc.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref oMissing); myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing); myWordDoc = null; myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing); myWordDoc = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); }
private void btnReplace_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(File_Replace)) { return; } object objFile = File_Replace; Word.Application app = new Word.ApplicationClass(); try { //设置为不可见 app.Visible = false; Word.Document doc = doc = app.Documents.Open(ref objFile, 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 replace = Word.WdReplace.wdReplaceAll; app.Selection.Find.Replacement.ClearFormatting(); app.Selection.Find.ClearFormatting(); app.Selection.Find.Text = txtReplaceFrom.Text.Replace(Environment.NewLine, "^p"); //需要被替换的文本 app.Selection.Find.Replacement.Text = txtReplaceTo.Text.Replace(Environment.NewLine, "^p"); //替换文本 //执行替换操作 app.Selection.Find.Execute( ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref replace, ref Nothing, ref Nothing, ref Nothing, ref Nothing); doc.Save(); doc.Close(); MessageBox.Show("替换完毕!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { //Close wordApp Component app.Quit(ref Nothing, ref Nothing, ref Nothing); } }
bool DOCXConvertToPDF(string sourceFile) { bool result = false; object sourcePath = sourceFile; object targetPath = GetFileName(sourceFile); object targetType = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF; //Word.WdExportFormat.wdExportFormatPDF; object paramMissing = Type.Missing; Word.ApplicationClass wordApplication = null; Word.Document wordDocument = null; try { wordApplication = new Word.ApplicationClass(); wordDocument = wordApplication.Documents.Open(ref sourcePath); if (wordDocument != null) { wordDocument.SaveAs(targetPath, targetType); result = true; } } catch { result = false; } finally { if (wordDocument != null) { wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing); wordDocument = null; } if (wordApplication != null) { wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null; } //ms solution is like this GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(result); }
public void Close() { if (Doc != null) { Doc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(Doc); Doc = null; } if (App != null) { App.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(App); App = null; } GC.Collect(); }
/// <summary>生成PDF文件</summary> public override bool Execute(string sourceFile, string destFile) { bool success = true; Microsoft.Office.Interop.Word.ApplicationClass application = null; Microsoft.Office.Interop.Word.Documents documents = null; Microsoft.Office.Interop.Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.ApplicationClass(); //Type wordType = application.GetType(); documents = application.Documents; // 打开文件 Type docsType = documents.GetType(); document = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, documents, new Object[] { sourceFile, true, true }); Type docType = document.GetType(); docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, document, new object[] { destFile, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML }); } catch (Exception) { success = false; } finally { if (document != null) { document.Close(); Marshal.ReleaseComObject(document); } if (application != null) { application.Quit(); Marshal.ReleaseComObject(application); } //关闭文档 //docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, document, new object[] { null, null, null }); //退出 Word //wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, application, null); } return(success); }
private void buttonImportFromDoc_Click(object sender, EventArgs e) { object filename = @"C:\source\repos\MyExam\MyExam\Resources\Exam PL-900 PowerApps.docx"; Microsoft.Office.Interop.Word.ApplicationClass AC = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document(); object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; try { doc = AC.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 isVisible, ref missing, ref missing, ref missing); Image[] images = new Image[AC.ActiveDocument.InlineShapes.Count]; for (int i = 0; i < AC.ActiveDocument.InlineShapes.Count; i++) { int m_i = i + 1; InlineShape inlineShape = AC.ActiveDocument.InlineShapes[m_i]; inlineShape.Select(); AC.Selection.Copy(); Computer computer = new Computer(); images[i] = computer.Clipboard.GetImage(); } ucXmlRichTextBoxQA.Xml = System.IO.File.ReadAllText(generateQAXMLforExam_PL_900_for_Import_docx(Regex.Replace(doc.Content.Text, @"\r\n?|\n?|\v?|\f", ""), images)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error is occured", MessageBoxButtons.OK); } finally { object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref doNotSaveChanges, ref missing, ref missing); AC.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(doc); System.Runtime.InteropServices.Marshal.ReleaseComObject(AC); GC.Collect(); } }
public void closeWordApp() { doc.Close(0); WordApp.Quit(); if (doc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(doc); } if (WordApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp); } doc = null; WordApp = null; }
/// <summary> /// 把Word文件转换成pdf文件 /// </summary> public bool WordToPdf(/*object sourcePath, string targetPath*/) { object docxPath = null; string pdfPath = null; docxPath = @"C:\Users\Zhang_weiwei\Desktop\第四周测试论文\基于eLAMP的Linux安全加固方案设计与实现张俊霞论文.docx"; pdfPath = @"C:\Users\Zhang_weiwei\Desktop\第四周测试论文\基于eLAMP的Linux安全加固方案设计与实现张俊霞论文.pdf"; bool result = false; WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF; object missing = Type.Missing; Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null; Document document = null; try { applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass(); document = applicationClass.Documents.Open(ref docxPath, 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(pdfPath, 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); }
private void word2PDF(object Source, object Target) { //Creating the instance of Word Application if (MSdoc == null) { MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass(); } try { MSdoc.Visible = false; MSdoc.Documents.Open(ref Source, 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, ref Unknown, ref Unknown); MSdoc.Application.Visible = false; MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize; object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; MSdoc.ActiveDocument.SaveAs(ref Target, ref format, 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, ref Unknown); } catch (Exception e) { MessageBox.Show(e.Message); } 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 MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown); } }
/// <summary> /// 打印预览 /// </summary> /// <param name="printName"></param> /// <returns></returns> public bool printView(string printName) { //打印 Microsoft.Office.Interop.Word.Application app = null; Microsoft.Office.Interop.Word.Document doc = null; object missing = System.Reflection.Missing.Value; object templateFile = printFilePath; try { app = new Microsoft.Office.Interop.Word.ApplicationClass(); doc = app.Documents.Add(ref templateFile, ref missing, ref missing, ref missing); //保存默认打印机 string defaultPrint = app.ActivePrinter; app.ActivePrinter = printName; //预览 app.Visible = true; doc.PrintPreview(); } catch (Exception exp) { object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;// .wdDoNotSaveChanges; if (doc != null) { doc.Close(ref saveChange, ref missing, ref missing); } if (app != null) { app.Quit(ref missing, ref missing, ref missing); } foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD")) { p.Kill(); } return(false); } return(true); }
/// <summary> /// Word格式转换(默认转成PDF) /// </summary> /// <param name="sourcePath">源路径</param> /// <param name="targetPath">目标路径</param> /// <param name="targetFileType">转换类型</param> /// <returns></returns> public static bool WordConvert(string sourcePath, string targetPath, WdExportFormat targetFileType = WdExportFormat.wdExportFormatPDF) { ApplicationClass wordApplication = null; Document wordDocument = null; try { var file = new FileInfo(sourcePath); var listP = System.Diagnostics.Process.GetProcessesByName("winword"); foreach (var p in listP.Where(p => p.MainWindowTitle.Contains(file.Name))) { p.Kill(); } wordApplication = new ApplicationClass(); wordDocument = wordApplication.Documents.Open(sourcePath); if (wordDocument != null) { wordDocument.SaveAs(targetPath, targetFileType); } } catch (Exception e) { Console.WriteLine(e.Message); throw; } finally { if (wordDocument != null) { wordDocument.Close(); } if (wordApplication != null) { wordApplication.Quit(); } GC.Collect(); GC.WaitForPendingFinalizers(); } return(true); }
static void Main(string[] args) { object path; string strContent; // 文本内容变量 MSWord.Application wordApp; // word 应用程序变量 MSWord.Document wordDoc; // word 文档变量 path = @"F:\xianfeng\MyWord.csv"; //后缀改为docx 则创建word 文档 wordApp = new MSWord.ApplicationClass(); if (File.Exists((string)path)) { File.Delete((string)path); } //由于使用的是COM 库,因此有许多变量需要用Misssing.Value 代替 Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //strContent = "您好!\n"; //wordDoc.Paragraphs.Last.Range.Text = strContent; //strContent = "hello world"; //wordDoc.Paragraphs.Last.Range.Text = strContent; //WdSaveFormat 为word 2007 文档的保存格式 object format = MSWord.WdSaveFormat.wdFormatDocumentDefault; //将wordDoc 文档对象保存为docx文档 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 文档对象 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); //关闭wordApp组件对象 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); Console.WriteLine(path + " 创建完毕"); }
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; }
/// <summary> /// Converts a Word document to PDF /// </summary> /// <param name="inputFile">The Word input file</param> /// <param name="outputFile">The PDF output file</param> /// <returns></returns> internal static void Convert(string inputFile, string outputFile) { DeleteAutoRecoveryFiles(); WordInterop.ApplicationClass word = null; WordInterop.DocumentClass document = null; try { word = new WordInterop.ApplicationClass { ScreenUpdating = false, DisplayAlerts = WordInterop.WdAlertLevel.wdAlertsNone, DisplayDocumentInformationPanel = false, DisplayRecentFiles = false, DisplayScrollBars = false, AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable }; word.Options.UpdateLinksAtOpen = false; word.Options.ConfirmConversions = false; word.Options.SaveInterval = 0; word.Options.SaveNormalPrompt = false; word.Options.SavePropertiesPrompt = false; word.Options.AllowReadingMode = false; word.Options.WarnBeforeSavingPrintingSendingMarkup = false; word.Options.UpdateFieldsAtPrint = false; word.Options.UpdateLinksAtOpen = false; word.Options.UpdateLinksAtPrint = false; document = (WordInterop.DocumentClass)Open(word, inputFile, false); // Do not remove this line!! // This is yet another solution to a weird Office problem. Sometimes there // are Word documents with images in it that take some time to load. When // we remove the line below the ExportAsFixedFormat method will be called // before the images are loaded thus resulting in an unendless loop somewhere // in this method. // ReSharper disable once UnusedVariable var count = document.ComputeStatistics(WordInterop.WdStatistic.wdStatisticPages); word.DisplayAutoCompleteTips = false; word.DisplayScreenTips = false; word.DisplayStatusBar = false; document.ExportAsFixedFormat(outputFile, WordInterop.WdExportFormat.wdExportFormatPDF); } finally { if (document != null) { document.Saved = true; document.Close(false); Marshal.ReleaseComObject(document); } if (word != null) { word.Quit(false); Marshal.ReleaseComObject(word); } } }
private bool word_convert_file(string source, string output,string file_type) { if (System.IO.File.Exists(source)) { //start conversion try { Microsoft.Office.Interop.Word.ApplicationClass MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass(); object paramSourceDocPath = source; object Unknown = Type.Missing; object paramTrue = true; object paramFalse = false; object paramExportFilePath = output; object paramSaveFormat = WdSaveFormat.wdFormatHTML; object paramEncoding = Encoding.ASCII; object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; //WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatPDF; switch (file_type) { case "pdf": //set exportformat to pdf format = WdSaveFormat.wdFormatPDF; break; case "html": //set exportformat to pdf format = WdSaveFormat.wdFormatHTML; break; } MSdoc.Documents.Open( ref paramSourceDocPath, ref Unknown, ref paramTrue, ref paramFalse, 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; MSdoc.ActiveDocument.SaveAs(ref paramExportFilePath, ref format, ref Unknown, ref Unknown, ref paramFalse, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges; MSdoc.Quit(ref saveChanges, ref Unknown, ref Unknown); //MSdoc.ActiveDocument.Close(ref Unknown, ref Unknown, ref Unknown); //MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown); //MSdoc.Quit(ref paramFalse, ref Unknown, ref Unknown); // MSdoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown); //MSdoc = null; } catch (Exception err) { errormessage=err.Message; } return true; } else { errormessage="ERROR: Inputfile not found"; } return false; }
void Download2() { Object Nothing = System.Reflection.Missing.Value; //取得Word文件保存路径 //string path = "Works/"; //string serverPath = Server.MapPath(path); string tempName = DateTime.Now.ToString("yyyyMMddHHMMss"); object filename = System.Web.HttpRuntime.AppDomainAppPath + "\\VoteProject\\WordDC\\" + tempName + ".doc"; //Response.Write(filename); //Response.End(); //创建一个名为WordApp的组件对象 Word.Application WordApp = new Word.ApplicationClass(); //创建一个名为WordDoc的文档对象 Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //增加一表格 //Word.Table table = WordDoc.Tables.Add(WordApp.Selection.Range, 1, 1, ref Nothing, ref Nothing); //在表格第一单元格中添加自定义的文字内容 //table.Cell(1, 1).Range.Text = "在表格第一单元格中添加自定义的文字内容"; //在文档空白地方添加文字内容 //WordDoc.Paragraphs.Last.Range.Bold = 72; //WordApp.Visible = true; //WordDoc.Activate(); #region 标题 WordApp.Selection.Font.Size = 15; WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // 居中 WordApp.Selection.Font.Bold = 1; // 黑体 WordApp.Selection.TypeText("D110"); #endregion #region 时间和来源 WordApp.Selection.TypeParagraph(); WordApp.Selection.Font.Size = 10; WordApp.Selection.Font.Bold = 0; // 取消黑体 WordApp.Selection.TypeText("发布时间:" + "2015-07-13" + " 来源:" + "本站"); #endregion #region 摘要 WordApp.Selection.TypeParagraph(); WordApp.Selection.TypeParagraph(); WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; // 居左 WordApp.Selection.TypeText("摘要:"); WordApp.Selection.TypeParagraph(); //WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 2.0f; //首行缩进2个字符 WordApp.Selection.TypeText(" " + "无"); #endregion #region 内容 WordApp.Selection.TypeParagraph(); WordApp.Selection.TypeParagraph(); WordApp.Selection.TypeText("内容:"); string strPageContent = ""; //将一个<br>变成两个<br> //strPageContent = Regex.Replace(strPageContent, "(<br>[\\s]*)+", "<br /><br />"); //将所有标签去掉,只剩下\r\n strPageContent = Regex.Replace(strPageContent, @"<[^>]+/?>|</[^>]+>", "", RegexOptions.IgnoreCase); string[] strContents = strPageContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string strContent in strContents) { WordApp.Selection.TypeParagraph(); WordApp.Selection.TypeText(" " + strContent); } #region 文章时可用 //string strPageContent = SaveShowInfo.Content.ToString(); ////将一个<br>变成两个<br> ////strPageContent = Regex.Replace(strPageContent, "(<br>[\\s]*)+", "<br /><br />"); ////将所有标签去掉,只剩下\r\n //strPageContent = Regex.Replace(strPageContent, @"<[^>]+/?>|</[^>]+>", "", RegexOptions.IgnoreCase); //string[] strContents = strPageContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //foreach (string strContent in strContents) //{ // WordApp.Selection.TypeParagraph(); // WordApp.Selection.TypeText(" " + strContent); //} #endregion #endregion //WordDoc.Paragraphs.Last.Range.Text += SaveShowInfo.PictureUrl; //将WordDoc文档对象的内容保存为DOC文档 WordDoc.SaveAs(ref filename, 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); //关闭WordDoc文档对象 WordDoc.Close(ref Nothing, ref Nothing, ref Nothing); //关闭WordApp组件对象 WordApp.Quit(ref Nothing, ref Nothing, ref Nothing); //返回结果 //lblMsg.Text = "文档路径:<a href='/c:\\111.doc'>c:\\111.doc</a>(点击链接查看)<br>生成结果:成功!"; Label1.Text = "文档路径:<a href='WordDC/" + tempName + ".doc'>" + tempName + ".doc</a>(点击链接查看)<br>生成结果:成功!"; ////使导出文件清除特殊符号 //string outFileName = si.Title.Replace("/", " "); //outFileName = outFileName.Replace("\\", " "); //outFileName = outFileName.Replace(":", " "); //outFileName = outFileName.Replace("*", " "); //outFileName = outFileName.Replace("?", " "); //outFileName = outFileName.Replace("\"", " "); //outFileName = outFileName.Replace("<", " "); //outFileName = outFileName.Replace(">", " "); //outFileName = outFileName.Replace("|", " "); }
public void load_playlist_oldFormat() { string path = BB080111; object template = path; object isNewTemplate = false; object documentType = 0; 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("blah"); IList<Einsatz> einsaetze = new List<Einsatz>(doc.Tables[1].Rows.Count); foreach(Row row in doc.Tables[1].Rows) { Track track = new Track( new Autor(init(brush(row.Cells[1].Range.Text))), new Bpm(null), new Code(init(brush(row.Cells[2].Range.Text))), new Interpret(init(brush(row.Cells[3].Range.Text))), new Label(init(brush(row.Cells[4].Range.Text))), new Laenge(init(brush(row.Cells[5].Range.Text))), new Titel(init(brush(row.Cells[6].Range.Text))), new Verlag(init(brush(row.Cells[7].Range.Text))), new Year(null), new Ending(Ending.Attribute.None)); einsaetze.Add(new Einsatz(playlist, track, row.Index)); } Assert.AreEqual(doc.Tables[1].Rows.Count, einsaetze.Count); object saveChanges = false; object originalFormat = false; object routeDocument = false; app.Quit(ref saveChanges, ref originalFormat, ref routeDocument); }
public Boolean WriteDocumentFromTemplet(String sTempletPath) { MSWord.ApplicationClass wordApp = new MSWord.ApplicationClass(); MSWord.Document wordDoc = null; object missing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = true; object TempletPath = sTempletPath; try { //Generate all documents, start from the 2nd line for (int i = 2; i <= intRows; i++) { Log("Create document for " + strData[i - 1, 0] + "..."); wordDoc = wordApp.Documents.Open(ref TempletPath, 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); for (int j = 1; j <= intCols; j++) { string[] sArray = strData[0, j - 1].Split('|'); foreach (string sBmk in sArray) { object bkObj = sBmk; //if (sArray.Length != 1) Log("Combined: " + strData[0, j - 1] + " contains " + sArray.Length + " bootmark , Finding -- " + sBmk); if (wordApp.ActiveDocument.Bookmarks.Exists(sBmk)) { wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select(); String s = strData[i - 1, j - 1]; int len = Encoding.Default.GetBytes(s).Length; //Log(s + " length: " + s.Length + ", bytes:" + len); wordApp.Selection.Delete(Type.Missing, len); wordApp.Selection.TypeText(strData[i - 1, j - 1]); } } } String personDirPath = WorkDirPath + @"\" + strData[i - 1, 0]; if (!Directory.Exists(personDirPath)) { Directory.CreateDirectory(personDirPath); } object sDocPath = personDirPath + @"\" + System.IO.Path.GetFileNameWithoutExtension(sTempletPath) + ".doc"; //object format = MSWord.WdSaveFormat.wdFormatDocumentDefault; object format = MSWord.WdSaveFormat.wdFormatDocument97; wordDoc.SaveAs(ref sDocPath, 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); wordDoc.Close(ref missing, ref missing, ref missing); } wordApp.Quit(ref missing, ref missing, ref missing); wordApp = null; Log("Create OK"); } catch (Exception e) { Log(sTempletPath + Environment.NewLine + "Excel App error:" + e.Message.ToString()); MessageBox.Show(sTempletPath + Environment.NewLine + " WordApp App error:" + e.Message.ToString()); return false; } finally { if (wordApp != null) { try { Kill(wordApp); Log("WordApp exited"); } catch (Exception e) { Log(sTempletPath + Environment.NewLine + " Kill WordApp exception " + e.Message); } } } return true; }
private void buttonWriteToDoc_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(imgFolder) || !Directory.Exists(imgFolder)) { MessageBox.Show("error"); ; } int imgCount= Directory.GetFiles(imgFolder, "*.jpg").Length; if (imgCount == 0) return; //word object srcFileName = Path.Combine(imgFolder, "image.doc"); object Nothing = System.Reflection.Missing.Value; object format = Word.WdSaveFormat.wdFormatDocument; Word.Application wordApp = new Word.ApplicationClass(); Word.Document wordDoc2= wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //Word.Document wordDoc2 = wordApp.Documents.Open(ref srcFileName, 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); try { int index = 0; while (index < imgCount) { string path = Path.Combine(imgFolder, index + ".jpg"); if (File.Exists(path)) { wordApp.Selection.InlineShapes.AddPicture(path, ref Nothing, ref Nothing, ref Nothing); } index++; } wordDoc2.SaveAs(ref srcFileName, 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); } catch { } finally { //关闭网页wordDoc2 wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing); if (wordDoc2 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2); wordDoc2 = null; } //关闭wordApp wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); if (wordApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); wordApp = null; } } GC.Collect(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
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); } }
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> /// 向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; }
/**/ /// <summary> /// 合并单元格 /// </summary> public static void CombinationCell() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add(ref beforeRow); Microsoft.Office.Interop.Word.Cell cell = newTable.Cell(2, 1);//2行1列合并2行2列为一起 cell.Merge(newTable.Cell(2, 2)); //cell.Merge( newTable.Cell( 1, 3 ) ); } /**/ /// <summary> /// 创建word文档 /// </summary> /// <returns></returns> public static string createWord() { Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Document WordDoc; string strContent = ""; object strFileName = docpath;//System.Web.HttpContext.Current.Server.MapPath("test.doc"); if (System.IO.File.Exists((string)strFileName)) System.IO.File.Delete((string)strFileName); Object oMissing = System.Reflection.Missing.Value; WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); #region 将数据库中读取得数据写入到word文件中 strContent = "你好\n\n\r "; WordDoc.Paragraphs.Last.Range.Text = strContent; strContent = "这是测试程序 "; WordDoc.Paragraphs.Last.Range.Text = strContent; #endregion //将WordDoc文档对象的内容保存为DOC文档 WordDoc.SaveAs(ref strFileName, 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文档对象 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); //关闭WordApp组件对象 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); string message = strFileName + "\r\n " + "创建成功 "; return message; }
// ---------------------------------------------------------------------------------- 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 bool DataConvert(string fileName, out string failTables, out string noPhotos) { string fileDir = fileName.Substring(0, fileName.LastIndexOf("\\")); string photoDir = fileName.Substring(0, fileName.LastIndexOf(".")) + "_Photos"; if (Directory.Exists(photoDir)) { Directory.Delete(photoDir, true); } Directory.CreateDirectory(photoDir); bool b = true; Microsoft.Office.Interop.Word.ApplicationClass appClass = null; Microsoft.Office.Interop.Word.Document doc = null; object path = fileName; object missing = System.Reflection.Missing.Value; int count = 0; failTables = ""; noPhotos = ""; try { appClass = new Microsoft.Office.Interop.Word.ApplicationClass(); appClass.Visible = false; doc = appClass.Documents.Open(ref path, 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); System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("RowNo", typeof(Int32)); dt.Columns.Add("IDCode", typeof(String)); //身份证编号 dt.Columns.Add("Name", typeof(String)); //姓名 dt.Columns.Add("Sex", typeof(String)); //性别 dt.Columns.Add("Nation", typeof(String)); //民族 dt.Columns.Add("Education", typeof(String)); //学历 dt.Columns.Add("Politics", typeof(String)); //政治面貌 dt.Columns.Add("WorkUnit", typeof(String)); //工作单位 dt.Columns.Add("Position", typeof(String)); //职务 dt.Columns.Add("PositionLevel", typeof(String)); //职级 dt.Columns.Add("JobTitle", typeof(String)); //职称 dt.Columns.Add("Compilation", typeof(String)); //编制 dt.Columns.Add("LawClass", typeof(String)); //执法种类 dt.Columns.Add("LawArea", typeof(String)); //执法区域 int rowNo = 1; foreach (Table table in doc.Tables) { count++; try { DataRow row = dt.NewRow(); row["RowNo"] = rowNo; row["Name"] = table.Cell(1, 2).Range.Text.Replace("\r\a", "").Trim().Replace(" ", ""); row["Sex"] = table.Cell(1, 4).Range.Text.Replace("\r\a", "").Trim(); row["Nation"] = table.Cell(2, 2).Range.Text.Replace("\r\a", "").Trim(); row["Education"] = table.Cell(2, 4).Range.Text.Replace("\r\a", "").Trim(); row["Politics"] = table.Cell(2, 6).Range.Text.Replace("\r\a", "").Trim(); row["WorkUnit"] = table.Cell(3, 2).Range.Text.Replace("\r\a", "").Trim(); row["Position"] = table.Cell(4, 2).Range.Text.Replace("\r\a", "").Trim(); row["PositionLevel"] = table.Cell(4, 4).Range.Text.Replace("\r\a", "").Trim(); row["JobTitle"] = table.Cell(4, 6).Range.Text.Replace("\r\a", "").Trim(); row["Compilation"] = table.Cell(4, 8).Range.Text.Replace("\r\a", "").Trim(); row["LawClass"] = table.Cell(5, 2).Range.Text.Replace("\r\a", "").Trim(); row["LawArea"] = table.Cell(5, 4).Range.Text.Replace("\r\a", "").Trim(); row["IDCode"] = table.Cell(6, 4).Range.Text.Replace("\r\a", "").Trim(); bool photoFlag = false; if (table.Cell(1, 7).Range.InlineShapes.Count != 0) { try { InlineShape shape = table.Cell(1, 7).Range.InlineShapes[1]; if (shape.Type == WdInlineShapeType.wdInlineShapePicture || shape.Type == WdInlineShapeType.wdInlineShapeLinkedPicture) { //利用剪贴板保存数据 shape.Select(); //选定当前图片 appClass.Selection.CopyAsPicture();//copy当前图片 if (Clipboard.ContainsImage()) { Image img = Clipboard.GetImage(); Bitmap bmp = new Bitmap(img); string imageName = photoDir + "\\" + row["IDCode"].ToString().Trim() + ".jpg"; int i = 2; while (File.Exists(imageName)) { imageName = photoDir + "\\" + row["IDCode"].ToString().Trim() + "(" + i + ").jpg"; i++; } EncoderParameters parameters = new EncoderParameters(1); EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,100L); parameters.Param[0] = parameter; ImageCodecInfo codecInfo=null; ImageCodecInfo[] codecInfos = ImageCodecInfo.GetImageEncoders(); codecInfo = codecInfos[1]; bmp.Save(imageName, codecInfos[1], parameters); //bmp.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg); photoFlag = true; } } } catch (Exception error) { photoFlag = false; } } if (!photoFlag) { noPhotos += "," + count; } dt.Rows.Add(row); rowNo++; } catch { failTables += "," + count; } } if (failTables.Length > 0) { failTables = failTables.Substring(1); } if (noPhotos.Length > 0) { noPhotos = noPhotos.Substring(1); } string excelName = fileName.Substring(0, fileName.LastIndexOf(".") + 1) + "xlsx"; b = DataTableToExcel(dt, excelName); if (b) { dgvData.DataSource = dt; } else { MessageBox.Show("生成Excel时发生错误", "提示"); } } catch (Exception err) { b = false; MessageBox.Show(err.Message, "异常"); } finally { Clipboard.Clear(); if (doc != null) { doc.Close(ref missing, ref missing, ref missing); } if (appClass != null) { appClass.Quit(ref missing, ref missing, ref missing); } GC.Collect(); } return b; }
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(); } }
// Gen biên bản đối chiếu dữ liệu lần 1 public static void Prc_BienBan(string _pathFOpen, string _pathFSave, string _short_name ) { using (CLS_DBASE.ORA _ora = new CLS_DBASE.ORA(GlobalVar.gl_connTKTQ)) { #region HEADER string _query_ps = "SELECT stt, tax_model, ten_tkhai, sotien FROM vw_bc_ps"; string _query_no = "SELECT stt, tax_model, tmt_ma_tmuc, so_no, so_pnop FROM vw_bc_no"; string _query_tcno = "SELECT STT, TAX_MODEL, TEN_TCNO, SO_NO FROM VW_BC_TCNO"; string _query_tphat = "SELECT STT, TAX_MODEL, SL, SOTIEN FROM VW_BC_TPHAT"; string _query_tphat_1 = "SELECT STT, TAX_MODEL FROM VW_BC_TPHAT"; string _query_tkh = "SELECT STT, TAX_MODEL, SL, DOANHTHU, GTTT, THUEPN FROM VW_BC_TKH"; string _query_tkh_1 = "SELECT STT, TAX_MODEL FROM VW_BC_TKH"; string _query_dkntk = "SELECT STT, TAX_MODEL, TEN_TKHAI, SL FROM VW_BC_DKNTK"; string _query_ckt = "SELECT STT, TAX_MODEL, TEN_TKHAI, SOTIEN FROM VW_BC_CKT"; string _query_tkmb = "SELECT STT, TAX_MODEL, ten_bac, SL, SOTIEN FROM VW_BC_TKMB"; string _query_tkmb_1 = "SELECT STT, TAX_MODEL, ten_bac FROM VW_BC_TKMB"; string _query_01pnn = "SELECT stt, TAX_MODEL, ma_tmuc, SL, SOTIEN FROM VW_BC_01PNN"; string _query_01pnn_1 = "SELECT stt, TAX_MODEL, ma_tmuc FROM VW_BC_01PNN"; string _query_02pnn = "SELECT stt, TAX_MODEL, ma_tmuc, SL, SOTIEN FROM VW_BC_02PNN"; string _query_02pnn_1 = "SELECT stt, TAX_MODEL, ma_tmuc FROM VW_BC_02PNN"; const int _row_start_1 = 4; Object _objNULL = System.Reflection.Missing.Value; Object _objTRUE = true; Object _objFALSE = false; String _query = null; DataTable _dt = null; string _txtField = null; // Đóng phiên làm việc Database _ora.TransStart(); // Mở kết nối đến CQT trong các câu lệnh query _query = "call PCK_MOI_TRUONG.prc_set_glview('" + _short_name + "')"; _ora.TransExecute(_query); // Tham số cho thứ tự của table trong WORD int _k; // Tham số cho thứ tự xóa table trong WORD int _z = 0; // Các index của table trong _Document cần xóa ArrayList _arr_delTable = new ArrayList(); // Mở một instance cho MS Word Microsoft.Office.Interop.Word.ApplicationClass _wordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); _wordApp.Visible = false; // Sao chép mẫu biên bản theo _pathFOpen Object _strFile = _pathFOpen; _Document _doc = _wordApp.Documents.Add(ref _strFile, //Template ref _objNULL, //NewTemplate ref _objNULL, //DocumentType ref _objFALSE //Visible ); #endregion #region IN DU LIEU #region In bảng phát sinh _k = 4; _dt = _ora.TransExecute_DataTable(_query_ps); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng nợ _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_no); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng tc nợ _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tcno); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng tính phạt _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tphat); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So CQT quản lý _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tphat_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So sai lệch _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tphat_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng tk khoán _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkh); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //Số CQT quản lý _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkh_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //Số sai lệch _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkh_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng dkntk _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_dkntk); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng còn khấu trừ _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_ckt); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng TKMB _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkmb); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So CQT quan ly _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkmb_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So sai lech _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_tkmb_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng 01 PNN _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_01pnn); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So CQT quan ly _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_01pnn_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So sai lech _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_01pnn_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion #region In bảng 02 pnn _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_02pnn); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So CQT quan ly _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_02pnn); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); //So sai lech _k = _k + 1; _dt = _ora.TransExecute_DataTable(_query_02pnn_1); Prc_fill_tbBienBan(_k, _doc, _dt, _row_start_1); // Add các index của table cần xóa if (_dt.Rows.Count == 0) _arr_delTable.Add(_k); _dt.Reset(); #endregion // Xóa table không cần thiết của _Document foreach (int i in _arr_delTable) { _doc.Tables[i - _z].Delete(); _z++; } #endregion #region END // Tính số trang của biên bản Microsoft.Office.Interop.Word.WdStatistic _stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages; int _countPage = _doc.ComputeStatistics(_stat, ref _objNULL); // Điền các giá trị MERGE MAIL #region MERGE MAIL _query = @"SELECT * FROM vw_bban_01"; _dt = _ora.TransExecute_DataTable(_query); foreach (Field _docField in _doc.Fields) { Microsoft.Office.Interop.Word.Range _rngFieldCode = _docField.Code; String _fieldText = _rngFieldCode.Text; if (_fieldText.StartsWith(" MERGEFIELD")) { // Kết quả _rngFieldCode.Text có dạng // MERGEFIELD MyFieldName \\* MERGEFORMAT Int32 _endMerge = _fieldText.IndexOf("\\"); Int32 _fieldNameLength = _fieldText.Length - _endMerge; String _fieldName = _fieldText.Substring(11, _endMerge - 11); // thực hiện thay thế các Fields foreach (DataColumn _col in _dt.Columns) { if (_col.ColumnName.ToString().Trim().ToLower().Equals(_fieldName.Trim().ToLower())) { foreach (DataRow _row in _dt.Rows) { _docField.Select(); _txtField = _row[_col].ToString(); //_txtField = _row[_col].ToString() + (_fieldName.Trim() == "fld_CQT1" ? " giữ 01 bản, " : ""); if ((_fieldName.Trim().ToUpper() == "fld_tax_model".ToUpper()) & _row[_col].ToString().ToUpper().Equals("QCT")) _txtField = @"QLT\QCT"; if (_fieldName.Trim().ToUpper() == "fld_CountPage".ToUpper()) _txtField = _countPage.ToString(); _wordApp.Selection.TypeText(CLS_FONT.Fnc_TCVN3ToUNICODE(_txtField)); } } } } } _dt.Reset(); #endregion // Save tài liệu Object _pathSaveFile = _pathFSave + "\\" + _short_name + "_BienBanDoiChieu_01.doc"; _doc.SaveAs(ref _pathSaveFile, //FileName ref _objNULL, //FileFormat ref _objNULL, //LockComments ref _objNULL, //Password ref _objNULL, //AddToRecentFiles ref _objNULL, //WritePassword ref _objNULL, //ReadOnlyRecommended ref _objNULL, //EmbedTrueTypeFonts ref _objNULL, //SaveNativePictureFormat ref _objNULL, //SaveFormsData ref _objNULL, //SaveAsAOCELetter ref _objNULL, //Encoding ref _objNULL, //InsertLineBreaks ref _objNULL, //AllowSubstitutions ref _objNULL, //LineEnding ref _objNULL //AddBiDiMarks ); // Đóng tài liệu _doc.Close(ref _objFALSE, ref _objNULL, ref _objNULL); // Thoát WORD _wordApp.Quit(ref _objNULL, ref _objNULL, ref _objNULL); // Đóng phiên làm việc Database _ora.TransCommit(); } #endregion }
/// <summary> /// WORD文档转换PDF格式文件 /// 创建人:张活生 /// 创建时间:2015年12月10日10:20:37 /// </summary> /// <param name="sourcePath">源文件路径</param> /// <param name="targetPath">目标文件路径</param> /// <returns>true:转换成功;false:转换失败</returns> public static bool DocConvertToPdf(string sourcePath, string targetPath) { bool result = false; WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF; object paramMissing = Type.Missing; ApplicationClass wordApplication = new ApplicationClass(); Document wordDocument = null; try { object paramSourceDocPath = sourcePath; string paramExportFilePath = targetPath; 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 = Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; 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); if (wordDocument != null) wordDocument.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); result = true; } catch { result = false; } finally { if (wordDocument != null) { wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing); wordDocument = null; } if (wordApplication != null) { wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return result; }
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; }