当前位置: 代码迷 >> C# >> 关于c#生成word
  详细解决方案

关于c#生成word

热度:27   发布时间:2016-05-05 04:08:49.0
关于c#生成word。

需求:需要把数据做成这样的效果、一个页面展示一个r单子数据。

 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
View Code
   #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
View Code
    #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
View Code
    #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
View Code

 

遇到的问题:

             1.由于需要每一个页面显示一个单子、所以每次根据ProcInstIDArr[]  循环创建完以后、调用InsertBreak()生成下一个空白页面、导致最后会出现一个空白页面、

      当时想到的是怎么删除最后一个空白页、通过在网上查询,说通过以下代码可以删除、最后拿下来试验发现无法实现。

 //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);
View Code

      中午跟同事请教:理理思路。发现完全是我想复杂了、只想着怎么删除,没有想过不去生成。最后通过一个if判断轻松解决问题。

      遇到问题不要想的太复杂。

      2.还有一个关于winword.exe进程未杀死的问题、    这个是今天早上发现的,早上打开服务器,发现服务器上出现N个word文档。进程里还有不下30个winword.exe进      程、详情点击

2楼Jehuty#39;
mark
1楼harrell
用Openxml的方式可能更好
Re: 小然丶
@harrell,因为这个是一个成型的,我只是后面接手过来修改的。
  相关解决方案