## Word文档导出

Word文档导出

    using MSWord = Microsoft.Office.Interop.Word;
    using System.IO;
    using System.Reflection;
    using System.Data.SqlClient;
    using Microsoft.Office.Interop.Word;
    using System.Data;
    using Newtonsoft.Json;
    class Program
    {
        static string LinkSting = "Data Source=LAPTOP-MRDELPNB;Initial Catalog=ExamSystem;User ID=sa;password=12345678";
        static void Main(string[] args)
        {
            object path;                              //文件路径变量
            string strContent;                        //文本内容变量
            MSWord.Application wordApp = new MSWord.Application();//Word应用程序变量 
            MSWord.Document wordDoc;                  //Word文档变量
            path = Environment.CurrentDirectory + "//Word_Print.doc";
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //页面设置
            wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//设置纸张样式为A4纸
            wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式为垂直方向
            wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式
            wordApp.ActiveWindow.View.Type =WdViewType.wdOutlineView;
            wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;//页眉中的文字右对齐
            #region 页码设置并添加页码
            //为当前页添加页码
            MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码
            pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//设置页码的风格,是Dash形还是圆形的
            pns.HeadingLevelForChapter = 0;
            pns.IncludeChapterNumber = false;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber = 0; //开始页页码?
            object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间
            object first = true;
            wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);
            #endregion
            object unite = MSWord.WdUnits.wdStory;
            //写入普通文本
            try
            {
                string Sql = "select TopicName,TopicId from Topic;select TopicId,OptionsName,OptionsYes from Options";
                using (SqlConnection conn=new SqlConnection(LinkSting))
                {
                    using (SqlDataAdapter Sda=new SqlDataAdapter(Sql, conn))
                    {
                        DataSet Ds = new DataSet();
                        Sda.Fill(Ds);
                        List<TopicModel> topicModels = JsonConvert.DeserializeObject<List<TopicModel>>(JsonConvert.SerializeObject(Ds.Tables[0]));
                        List<OptionsModel> OptionsModel = JsonConvert.DeserializeObject<List<OptionsModel>>(JsonConvert.SerializeObject(Ds.Tables[1]));
                        //写入15号字体文本![在这里插入图片描述](https://img-blog.csdnimg.cn/20200930163445513.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80ODAwMjY2OQ==,size_16,color_FFFFFF,t_70#pic_center)

                        strContent = "考试\n";
                        wordApp.Selection.EndKey(ref unite, ref Nothing);
                        wordDoc.Paragraphs.Last.Range.Font.Size = 15;
                        wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                        wordDoc.Paragraphs.Last.Range.Text = strContent;
                        string Da = "";
                        for (int i = 0; i < topicModels.Count; i++)
                        {
                            wordDoc.Paragraphs.Last.Range.Text += $"{i+1}.{topicModels[i].TopicName}()";
                            List< OptionsModel > optionsModels= OptionsModel.Where(s => s.TopicId == topicModels[i].TopicId).ToList();
                            for (int j = 0; j < optionsModels.Count; j++)
                            {
                                wordDoc.Paragraphs.Last.Range.Text += $"{Convert.ToChar(j+65)}.{optionsModels[j].OptionsName}";
                                Da += optionsModels[j].OptionsYes;
                                if (j== optionsModels.Count-1)
                                {
                                    wordDoc.Paragraphs.Last.Range.Text += $"答案:{Da}";
                                    Da = "";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {

                throw;
            }
            wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
            //wordDoc.Content.InsertAfter("\n");
            wordDoc.Content.InsertAfter(DateTime.Now.ToLongDateString());
            //WdSaveFormat为Word 2003文档的保存格式
            object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是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.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭wordApp组件对象
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadKey();
        }

导出效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值