.net动态生成word文档,并下载

哇,博客终于审批通过啦!赶紧不忘过来写篇博文纪念一下!!哈哈

其实开通这个博客一方面是希望养成自己良好的学习习惯,另一方面也是以往总是自己默默的单方面的得到其它博友们的帮助,长此以往,心里过意不去,所以也想把自己平时遇到的难题或经验还是小方法也跟大家分享一下,哦啦!

费话不多说,正题!

最近在做一个网上报名考试网站,里面涉及到准考证的打印,想说把准考证信息动态生成文本文档,供考生下载这么一个功能,走了一些弯路,下面把我的成果分享给大家,希望帮助到一些正在经历类似难题的亲们……

首先,要创建word对象

创建之前别忘了引用
using Microsoft.Office.Interop.Word;

Object Nothing = System.Reflection.Missing.Value;

        //创建Word文档
        Application WordApp = new ApplicationClass();
        Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

        //添加页眉
        WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
        WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
        WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
        WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
        WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置

        WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距

        //移动焦点并换行
        object count = 8;
        object WdLine = WdUnits.wdLine;//换一行;
        WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
        WordApp.Selection.TypeParagraph();//插入段落

        //文档中创建表格
        Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 8, 3, ref Nothing, ref Nothing);

        //设置表格样式
        newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleThickThinLargeGap;
        newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
        newTable.Columns[1].Width = 100f;
        newTable.Columns[2].Width = 220f;
        newTable.Columns[3].Width = 105f;


            //填充表格内容
            newTable.Cell(1, 1).Range.Text = row["posname"].ToString() + "考试准考证";
            newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
            newTable.Cell(1, 1).Height = 30;
            newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
            newTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
            WordApp.Selection.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

            //填充表格内容
            newTable.Cell(2, 1).Range.Text = "姓名";
            newTable.Cell(2, 2).Range.Text = "xxxx";

            newTable.Cell(3, 1).Range.Text = "身份证号";
            newTable.Cell(3, 2).Range.Text = "xxxx";

            newTable.Cell(4, 1).Range.Text = "准考证号";
            newTable.Cell(4, 2).Range.Text = "xxxx";

            newTable.Cell(5, 1).Range.Text = "考点名称";
            newTable.Cell(5, 2).Range.Text = "xxxx";

            newTable.Cell(6, 1).Range.Text = "考点地址";
            newTable.Cell(6, 2).Range.Text = "xxxx";

            newTable.Cell(7, 1).Range.Text = "考试座位";
            newTable.Cell(7, 2).Range.Text = "xxxx";

            newTable.Cell(8, 1).Range.Text = "考试时间";
            newTable.Cell(8, 2).Range.Text = "xxxx";

 到这里为此,一个简单的文档大致就成型了,如果需要在本文档里加入图片的话呢,请看下面:

           //纵向合并单元格
            newTable.Cell(2, 3).Select();//选中一行
            object moveUnit = WdUnits.wdLine;
            object moveCount = 6;
            object moveExtend = WdMovementType.wdExtend;
            WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
            WordApp.Selection.Cells.Merge();
            newTable.Cell(2, 3).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
            WordApp.Selection.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

            //插入图片
            string FileName = "E:\123.jpg";//图片所在路径
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = WordDoc.Application.Selection.Range;
            WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
            WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 80f;//图片宽度
            WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 110f;//图片高度
            //将图片设置为四周环绕型
            Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
            s.WrapFormat.Type = WdWrapType.wdWrapSquare;
           
            WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
            WordDoc.Paragraphs.Last.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

             string name = "123.doc";
            object filename = Server.MapPath("TicketFile") + "\" + name;  //文件保存路径

            //文件保存
            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);
           
            if(WordDoc != null)
            {
                WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                WordDoc = null;
            }
            if (WordApp != null)
            {
                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

                WordApp = null;
            }

写到这里,整个文档的生成就大功告成了,不过这其中我有个疑惑,就是在关闭文档时,我之前的代码是这样的

      WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
这么写之后,老是在quit这里报错,后面改成上面那种样子之后,不知道是不是因为这个原因,“莫名奇妙”地就好了 ,有哪个高手给我解释一下!!!嘿嘿     

   如果想把该 文档直接下载到本地的话,就简单了,相信大家都会,我把代码粘在下面: 

           string path = Server.MapPath("TicketFile/") + name;
            FileInfo fi = new FileInfo(path);
            if (fi.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(name));
                Response.AddHeader("Content-Length", fi.Length.ToString());
                Response.ContentType = "application/octet-stream;charset=gb2321";
                Response.WriteFile(fi.FullName);
                Response.Flush();
                Response.Close();
            }
        }

好了好了,这就是我弄了两天的东西,呵呵,菜鸟一个,希望能对大家有帮助,少走弯路!!!

原文地址:https://www.cnblogs.com/moonlightfang/p/3671404.html