需求:須要把數據作成這樣的效果、一個頁面展現一個r單子數據。html
object filename = ""; Object Nothing = System.Reflection.Missing.Value; Word.Application WordApp = new Word.ApplicationClass();//實例化word HY.Common.Utils.Logger.Log.Info("WordApp:" + WordApp); Word._Application oWord = new Word.Application(); //建立Word文檔 Word._Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); try { SetPage(WordApp, WordDoc, "橫板", 21, 29.7, 1, 1, 1, 1); HY.Common.Utils.Logger.Log.Info("WordDoc:" + WordDoc); string name = "審批表" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToLongTimeString().Replace(":", "") + ".docx";//建立生成文件名字 HY.Common.Utils.Logger.Log.Info("name" + name); string CreateFilePath = ConfigurationManager.AppSettings["CreateFilePath"]; HY.Common.Utils.Logger.Log.Info("CreateFilePath" + CreateFilePath); filename = CreateFilePath + name; //文件保存路徑 HY.Common.Utils.Logger.Log.Info("filename" + filename); string[] SerialNumberArr = Context.Request["SerialNumber"].Substring(0, Context.Request["SerialNumber"].ToString().Length - 1).Split(','); string[] ProcInstIDArr = Context.Request["ProcInstID"].Substring(0, Context.Request["ProcInstID"].ToString().Length - 1).Split(',');//掛帳Id string[] PaymentProcInstIDArr = Context.Request["PaymentProcInstID"].Substring(0, Context.Request["PaymentProcInstID"].ToString().Length - 1).Split(',');//付款Id for (int i = 0; i < ProcInstIDArr.Length; i++) { #region 打印 InsertText(WordDoc, " 審批表 ", new System.Drawing.Font("微軟雅黑", 12, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); InsertText(WordDoc, "", new System.Drawing.Font("微軟雅黑", 12, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, true); InsertText(WordDoc, "申請人信息", new System.Drawing.Font("宋體", 12, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); if (ProcInstIDArr.Length - 1 != i) { InsertBreak(WordDoc, Nothing); } #endregion } 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); WordApp = null; HY.Common.Utils.Logger.Log.Info("SaveAs" + filename); } catch (Exception ex) { HY.Common.Utils.Logger.Log.Info("error" + e.ToString()); } finally { WordDoc.Close(ref Nothing, ref Nothing, ref Nothing); oWord.Quit(ref Nothing, ref Nothing, ref Nothing); KillWordProcess(); }
#region - 插入文本 - public static bool InsertText(Word._Document oDoc, string strText, System.Drawing.Font font, Word.WdParagraphAlignment wdAlign, bool isAftre) { try { Word.Range rng = oDoc.Content; int lenght = oDoc.Characters.Count - 1; object start = lenght; object end = lenght; rng = oDoc.Range(ref start, ref end); if (isAftre == true) { strText += "\r\n"; } rng.Text = strText; rng.Font.Name = font.Name; rng.Font.Size = font.Size; if (font.Style == System.Drawing.FontStyle.Bold) { rng.Font.Bold = 1; } //設置單元格中字體爲粗體 rng.ParagraphFormat.Alignment = wdAlign;//設置文本對齊格式(左對齊,右對齊,居中) return true; } catch (Exception) { return false; } } #endregion
#region - 插入分頁符 - public static void InsertBreak(Word._Document WordDoc, Object Nothing) { Word.Paragraph para; para = WordDoc.Content.Paragraphs.Add(ref Nothing); object pBreak = (int)Word.WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak); } public static void DeleteBreak(Word.Application wordApp, Object Nothing) { Word.Range range1, range2; // 跳轉種類 object objWhat = Word.WdGoToItem.wdGoToPage; // 跳轉位置 object objWhich = Word.WdGoToDirection.wdGoToLast; // 轉向最後一頁 wordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing); // Range取得 range1 = wordApp.Selection.Range; range2 = wordApp.ActiveDocument.Range(ref Nothing, ref Nothing); object start = range1.Start; object end = range2.End; // 刪除最後一頁 wordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing); } #endregion
#region - 頁面設置 - public static void SetPage(Word.Application oWord, Word._Document oDoc, string orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin) { Logger.Log.Info("Word.Name" + oWord.Name); Logger.Log.Info("oDoc" + oDoc); oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width); oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height); if (orientation == "橫板") { oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; } oDoc.PageSetup.TopMargin = (float)(topMargin * 25);//上邊距 oDoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左邊距 oDoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右邊距 oDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下邊距 } #endregion
#region - 清除word進程 - /**/ /// <summary> /// 清除word進程 /// </summary> public static void KillWordProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses(); foreach (System.Diagnostics.Process p in myPs) { if (p.Id != 0) { string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString(); try { if (p.Modules != null) if (p.Modules.Count > 0) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS += "/n Modules[0].FileName:" + pm.FileName; myS += "/n Modules[0].ModuleName:" + pm.ModuleName; myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString(); if (pm.ModuleName.ToLower() == "winword.exe") p.Kill(); } } catch { } finally { } } } } #endregion
遇到的問題:服務器
1.因爲須要每個頁面顯示一個單子、因此每次根據ProcInstIDArr[] 循環建立完之後、調用InsertBreak()生成下一個空白頁面、致使最後會出現一個空白頁面、ide
當時想到的是怎麼刪除最後一個空白頁、經過在網上查詢,說經過如下代碼能夠刪除、最後拿下來試驗發現沒法實現。字體
//Word.Range range1, range2; //// 跳轉種類 //object objWhat = Word.WdGoToItem.wdGoToPage; //// 跳轉位置 //object objWhich = Word.WdGoToDirection.wdGoToLast; //// 轉向最後一頁 //WordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing); //// Range取得 //range1 = WordApp.Selection.Range; //range2 = WordApp.ActiveDocument.Range(ref Nothing, ref Nothing); //object start = range1.Start; //object end = range2.End; //// 刪除最後一頁 //WordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing);
中午跟同事請教:理理思路。發現徹底是我想複雜了、只想着怎麼刪除,沒有想過不去生成。最後經過一個if判斷輕鬆解決問題。ui
遇到問題不要想的太複雜。 spa
2.還有一個關於winword.exe進程未殺死的問題、 這個是今天早上發現的,早上打開服務器,發現服務器上出現N個word文檔。進程裏還有不下30個winword.exe進 程、詳情點擊code