C#对Word的一系列操作

工作已经半年了,在这半年中遇到最大的难题还是对WORD的一系列操作。在这里我总结一下自己对WORD的操作用法。

        

         //保存数据到Word中

         private void SaveToWord()
        {
            //保存Word
            Microsoft.Win32.SaveFileDialog saveFileDialog1 = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog1.Filter = "doc   files   (*.doc)|*.doc|docx   files   (*.docx)|*.docx|All   files   (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "保存试卷";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.CreatePrompt = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.FileName = dataTableList[0].Rows[0][TP0501.PAPER_NM].ToString();
            _importToWordPaperName.Add(dataTableList[0].Rows[0][TP0501.PAPER_NM].ToString());
            //创建Word文档
            if (saveFileDialog1.ShowDialog() == true)
            {
               //填充WORD中的内容
               ......
             }

            String localFilePath = saveFileDialog1.FileName.ToString();
            String filePath = localFilePath.Substring(0, localFilePath.LastIndexOf("//"));

            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref filename, ref Nothing, ref Nothing, ref Nothing);

            //为该Word添加页码
            object oAlignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
            object oFirstPage = true;
            oAlignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
            WordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref   oAlignment, ref   oFirstPage);
            WordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.NumberStyle = Microsoft.Office.Interop.Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;

            //文件保存
            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)
            {
                Marshal.ReleaseComObject(WordDoc);
                WordDoc = null;
            }
            WordApp.NormalTemplate.Saved = true;
            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);            
        }

 

        //将Word转换为B4页面类型、横向、分栏

        private void ChangeIntoB4(object file)
        {
            Object Nothing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application WordApp = null;
            Microsoft.Office.Interop.Word.Document WordDoc = null;
            try
            {
                WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                WordDoc = WordApp.Documents.Add(ref file, ref Nothing, ref Nothing, ref Nothing);

                //页面样式(A4--B4)
                WordDoc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperB4;
                //横版or竖版
                WordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                //页面分2栏
                //WordDoc.PageSetup.TextColumns.SetCount(2);
                //不双面打印
                WordDoc.PageSetup.TwoPagesOnOne = false;
                //文件保存
                WordDoc.SaveAs(ref file, 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 (COMException e)
            {
                MsgDialog.ShowMessage(e.Message);
            }
            finally
            {
                if (WordDoc != null)
                {
                    Marshal.ReleaseComObject(WordDoc);
                    WordDoc = null;
                }
                WordApp.NormalTemplate.Saved = true;
                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
        }

 

 

        //打印Word

        private void PrintWord(object printFile)
        {
            Microsoft.Office.Interop.Word.Application WordApp = null;
            Microsoft.Office.Interop.Word.Document WordDoc = null;
            object missing = System.Reflection.Missing.Value;
            //试卷Word出错MSG
            string errWord = string.Empty;
            try
            {
                WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                WordDoc = WordApp.Documents.Add(ref printFile, ref missing, ref missing, ref missing);
                //打印
                object background = true;
                WordDoc.PrintOut(ref background, 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, ref missing, ref missing);
                System.Threading.Thread.Sleep(5000);
            }
            catch (Exception exp)
            {
                errWord = "试卷打印出错!" + exp.Message + "/n";
            }
            finally
            {
                try
                {
                    object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;

                    if (WordDoc != null)
                    {
                        Marshal.ReleaseComObject(WordDoc);
                        WordDoc = null;
                    }

                    if (WordApp != null)
                        WordApp.Quit(ref saveChange, ref missing, ref missing);
                }
                catch (Exception ee)
                {

                }
            }
        }

 

        //将数据导出到Word中(绘制表格)

        private void ExportStu(List<string> liststu, List<string> listEducation, List<string> listPlusn, string path)
        {
           Object Nothing = System.Reflection.Missing.Value;
        //    Directory.CreateDirectory("f:/CNSI"); //创建文件所在目录
        //    string name = "CNSI.doc";
        //    object filename = "f://CNSI//" + name; //文件保存路径

            object filename = (object)path; //文件保存路径
            //创建Word文档
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.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 = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
            WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置

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

            //移动焦点并换行
            object count = 14;
            object WdLine = Microsoft.Office.Interop.Word.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, 15, 5, ref Nothing, ref Nothing);
            newTable.Select();
          //  WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居
            WordApp.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;//表格居中

 

            //设置表格样式
            newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
            newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            newTable.Columns[1].Width = 100f;
            newTable.Columns[2].Width = 100f;
            newTable.Columns[3].Width = 100f;
            newTable.Columns[4].Width = 100f;
            newTable.Columns[5].Width = 100f;

            //填充表格内容
            newTable.Cell(1, 1).Range.Text = "学生信息一览表";
            newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
            //合并单元格
            newTable.Cell(1, 1).Merge(newTable.Cell(1, 5));
            WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
            WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

            //填充表格内容
            newTable.Cell(2, 1).Range.Text = "一、学生基本信息:";
            newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
            //合并单元格
            newTable.Cell(2, 1).Merge(newTable.Cell(2, 5));
            WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

 

            //填充表格内容
            newTable.Cell(3, 1).Range.Text = "学号:";
            newTable.Cell(3, 2).Range.Text = liststu[0];
            newTable.Cell(3, 3).Range.Text = "姓名:";
            newTable.Cell(3, 4).Range.Text = liststu[1];

            newTable.Cell(4, 1).Range.Text = "性别:";
            newTable.Cell(4, 2).Range.Text = liststu[2];
            newTable.Cell(4, 3).Range.Text = "出生日期:";
            newTable.Cell(4, 4).Range.Text = liststu[6];

            newTable.Cell(5, 1).Range.Text = "进校日期:";
            newTable.Cell(5, 2).Range.Text = liststu[13];
            newTable.Cell(5, 3).Range.Text = "籍贯:";
            newTable.Cell(5, 4).Range.Text = liststu[4];

            newTable.Cell(6, 1).Range.Text = "班级:";
            newTable.Cell(6, 2).Range.Text = liststu[14];
            newTable.Cell(6, 3).Range.Text = "政治面目:";
            newTable.Cell(6, 4).Range.Text = liststu[5];

            newTable.Cell(7, 1).Range.Text = "手机:";
            newTable.Cell(7, 2).Range.Text = liststu[7];
            newTable.Cell(7, 3).Range.Text = "家庭电话:";
            newTable.Cell(7, 4).Range.Text = liststu[10];

            newTable.Cell(8, 1).Range.Text = "户口所在地:";
            newTable.Cell(8, 2).Range.Text = liststu[9];
            newTable.Cell(8, 3).Range.Text = "邮编:";
            newTable.Cell(8, 4).Range.Text = liststu[11];

            newTable.Cell(9, 1).Range.Text = "EMAIL:";
            newTable.Cell(9, 2).Range.Text = liststu[12];
            newTable.Cell(9, 3).Range.Text = "民族:";
            newTable.Cell(9, 4).Range.Text = liststu[4];

            newTable.Cell(10, 1).Range.Text = "级:";
            newTable.Cell(10, 2).Range.Text = liststu[15];
            newTable.Cell(10, 3).Range.Text = "年级:";
            newTable.Cell(10, 4).Range.Text = liststu[16];


            newTable.Cell(11, 1).Range.Text = "家庭住址:";
            newTable.Cell(11, 2).Range.Text = liststu[8];
            newTable.Cell(11, 2).Merge(newTable.Cell(11, 4));

 

            //纵向合并单元格
            newTable.Cell(3, 5).Select();//选中一行
            object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            object moveCount = 8;
            object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
            WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
            WordApp.Selection.Cells.Merge();
            插入图片
            //string FileName = @"f:/ml.jpg";//图片所在路径 "..//..//Images//学生照片.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 = 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;

            newTable.Cell(12, 1).Range.Text = "二、教育经历:";
            newTable.Cell(12, 1).Merge(newTable.Cell(12, 5));


            //newTable.Cell(13, 1).Merge(newTable.Cell(13, 5));
            //newTable.Cell(13, 1).Height = 60;
            //newTable.Cell(13, 1).Select();//选中一行

            object row = 0;
            if (listEducation.Count > 0)
            {
               newTable.Cell(13, 1).Merge(newTable.Cell(13, 5));
                newTable.Cell(13, 1).Height = 60;
                newTable.Cell(13, 1).Select();//选中一行
                int num = listEducation.Count;
                row = 3 * num;
                object con = 4;
                newTable.Cell(13, 1).Split(ref row, ref con);
                for (int y = 0; y < (int)row; y += 3)
                {
                    string str = listEducation[y / 3];
                    String[] kkk = str.Split(';');
                    //    Education1 += begin_time + ";" + end_time + ";" + school_nm + ";" + class_nm + ";" + charge_tchr_nm + ";" + status;

                    newTable.Cell(15 + y, 2).Merge(newTable.Cell(15 + y, 4));
                    newTable.Cell(15 + y, 2).Height = 45;

                    newTable.Cell(13 + y, 1).Range.Text = "起止时间:";
                    newTable.Cell(13 + y, 2).Range.Text = kkk[0] + "-" + kkk[1];
                    newTable.Cell(13 + y, 3).Range.Text = "毕业学校:";
                    newTable.Cell(13 + y, 4).Range.Text = kkk[2];

                    newTable.Cell(14 + y, 1).Range.Text = "班能名称:";
                    newTable.Cell(14 + y, 2).Range.Text = kkk[3];
                    newTable.Cell(14 + y, 3).Range.Text = "班主任:";
                    newTable.Cell(14 + y, 4).Range.Text = kkk[4];

                    newTable.Cell(15 + y, 1).Range.Text = "在校情况:";
                    newTable.Cell(15 + y, 2).Range.Text = kkk[5];

                }
            }
            else
            {
                int num = listEducation.Count;
                 row =1;
                 newTable.Cell(13, 1).Merge(newTable.Cell(13, 5));
                 newTable.Cell(13, 1).Height = 20;
           
            }

            int jz = 13 + (int)row;
            newTable.Cell(jz, 1).Range.Text = "三、奖惩信息:";
            newTable.Cell(jz, 1).Merge(newTable.Cell(jz, 5));
            jz++;
            newTable.Cell(jz, 1).Merge(newTable.Cell(jz, 5));
            newTable.Cell(jz, 1).Height = 50;

            newTable.Cell(jz, 1).Select();//选中一行


            if (listPlusn.Count > 0)
            {
                int num2 = listPlusn.Count;
                object row2 = 2 * num2;
                object con2 = 4;
                newTable.Cell(jz, 1).Split(ref row2, ref con2);
          
                for (int y = 0; y < (int)row2; y += 2)
                {
                    string str = listPlusn[y / 2];
                    String[] kkk = str.Split(';');
                    // Plusn1 += occur_time + ";" + append_type_cd + ";" + append_content;

                    newTable.Cell(jz + 1 + y, 2).Merge(newTable.Cell(jz + 1 + y, 4));
                    newTable.Cell(jz + 1 + y, 2).Height = 45;

                    newTable.Cell(jz + y, 1).Range.Text = "奖惩时间:";
                    newTable.Cell(jz + y, 2).Range.Text = kkk[0];
                    newTable.Cell(jz + y, 3).Range.Text = "类型:";
                    newTable.Cell(jz + y, 4).Range.Text = kkk[1];

                    newTable.Cell((jz + y + 1), 1).Range.Text = "内容:";
                    newTable.Cell((jz + y + 1), 2).Range.Text = kkk[2];
                }
            }
            //在表格中增加行
            //   WordDoc.Content.Tables[1].Rows.Add(ref Nothing);
        

            WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
            WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

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

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值