c#/.net操作word插入表格实例

先给张效果图---



整体是一个模板,第一个表格是替换里面的值,第二个直接动态生成插入。

。。。代码

using Abase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using UltraUtility;
using NewCityGardenERP.Model.Sale;
using NewCityGardenERP.Model;
namespace NewCityGardenERP.Handler.ProjectManage
{
    /// <summary>
    /// JSDHandler 的摘要说明
    /// </summary>
    public class JSDHandler : AdminBaseHttpHandler
    {
        List<TYYHCostOrder> ts;
        decimal htPriceSum = 0;
        decimal xzPriceSum = 0;
        public override void ProcessRequest(HttpContext context)
        {
            int ProjectId = Request["ProjectId"].ToInt();
            int ProjectType = Request["ProjectType"].ToInt();

            ts = NewCityGardenERP.DB.GetOrderByProjectDB.GetTYJSOrderByProject(ProjectId, 1);
            //if (ProjectType == 1)
            //{
            //}
            //else if (ProjectType == 2)
            //{
            //    NewCityGardenERP.DB.GetOrderByProjectDB.GetTYJSOrderByProject(ProjectId, 2);
            //}

            string filepath = Server.MapPath("/Fileupload/") + "jisuandan.doc";

            CreateWord(filepath);
            if (ts.Count > 0)
            {
                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("{ProjectName}", ts[0].ProjectName);
                datas.Add("{TYJSContractNumber}", ts[0].TYJSContractNumber);
                datas.Add("{ContractPrice}", ts[0].cPrice.ToString());
                datas.Add("{XZPrice}", xzPriceSum.ToString());
                datas.Add("{ZJPrice}", (htPriceSum + xzPriceSum).ToString());
                tihuan(datas);
            }
            else
            {
                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("{ProjectName}", "");
                datas.Add("{TYJSContractNumber}", "");
                datas.Add("{ContractPrice}", "");
                datas.Add("{XZPrice}", "");
                datas.Add("{ZJPrice}", "");
                tihuan(datas);
            }
            
            daochu();

        }

 
        //创建word
        Word.Application WordApp;
        Word.Document WordDoc;
        object Nothing;
        object unite = Word.WdUnits.wdStory;
        object filename;
        object oMissing;

        public string CreateWord(string name)
        {
            Nothing = System.Reflection.Missing.Value;
            filename = name;

            WordApp = new Word.Application();
            //WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //WordApp.Selection.PageSetup.LeftMargin = 50f;
            //WordApp.Selection.PageSetup.RightMargin = 50f;
            //WordApp.Selection.PageSetup.PageWidth = 650f;  //页面宽度 

            object fileName = Server.MapPath("template.doc");//模板文件
            //打开模板文件
            oMissing = System.Reflection.Missing.Value;
            WordDoc = WordApp.Documents.Open(ref fileName,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            darwText();
            darwTable();
            return "sdf";
        }

        public void daochu()
        {
            try
            {
              
                //准备导出word
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "utf-8";
                Response.AddHeader("Content-Disposition", "attachment;filename=结算单" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType = "application/ms-word";
                Response.End();
                killAllProcess();
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
            }
            catch (Exception ex)
            {

            }
            finally
            {
            
                //如果文件存在则输出到客户端
                if (File.Exists(filename.ToString()))
                {
                    Response.WriteFile(filename.ToString());
                }
            }
        }
        public void exitSave()
        {
            try
            {
                //object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
                //保存文档
                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);
                //准备导出word
                //Response.Clear();
                //Response.Buffer = true;
                //Response.Charset = "utf-8";
                //Response.AddHeader("Content-Disposition", "attachment;filename=结算单" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
                //Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                //Response.ContentType = "application/ms-word";
                //Response.End();
                //killAllProcess();
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (WordDoc != null)
                {
                    WordDoc.Close();//关闭word文档
                }
                if (WordApp != null)
                {
                    WordApp.Quit();//退出word应用程序
                }
              
            }
        }
        public void darwText()
        {
            //setFontBold(2);
            //setFontSize(20f);
            //setFontName("宋体");
            //setLineSpacing(20f);
            //chaRuDuLuo();
            setLineCount(14);
            //Move(14);
            //setText("庭院提升建设验收结算确认书\n");
            //endKey();
            //InsertLineBreak();
            //InsertLineBreak();

            setLineCount(1);
            checkLine();
            checkLine();
            checkLine();
            //setLineSpacing(2f);
            //setFontBold(0);
            //setFontSize(12f);
            //setFontName("宋体");
            //setText("关于___________________(项目名称)(合同编号:            ),我司已按合同在约定时间内完成了全部工程量,经双方现场确认,质量合格,符合协议约定标准。现我司申请按合同做如下结算:");

            //endKey();
            //InsertLineBreak();
            //chaRuDuLuo();
            setFontBold(0);
            setFontSize(12f);
            setFontName("宋体");
            文档中创建表格 
            //setLineSpacing(40f);
            //Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 6, 2, ref Nothing, ref Nothing);


            设置表格样式 
            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 

            设置表格框
            //newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            //newTable.Columns[1].Width = 200f;//设置表格列的宽度
            //newTable.Columns[2].Width = 350f;//设置表格列的宽度


            填充表格内容 
            //for (int k = 1; k < 6; k++)
            //{
            //    newTable.Rows[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            //}
            //for (int k = 1; k < 2; k++)
            //{
            //    newTable.Columns[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            //}
            垂直居中
            //object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            //object countjz = 1;
            //WordApp.Selection.MoveEnd(ref unit, ref countjz);
            //WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 

            填充表格内容 第一行
            //newTable.Cell(1, 1).Range.Text = "合同内结算金额";
            //newTable.Cell(2, 1).Range.Text = "签证结算价金额";
            //newTable.Cell(3, 1).Range.Text = "合计结算总金额";
            //newTable.Cell(4, 1).Range.Text = "已付预付款金额";
            //newTable.Cell(5, 1).Range.Text = "质保金";
            //newTable.Cell(6, 1).Range.Text = "本次应付金额";
            //setLineSpacing(1f);
            //endKey();
            //InsertLineBreak();
            //setText("甲方签字或盖章:                                          乙方签字或盖章:");
            //endKey();
            //InsertLineBreak();
            //setText("日          期:                                           日          期:");
            //------------------------------------注释有用--------------------------------------------------//

            //setStyte(WordApp, WordDoc, Nothing,2, 18f, 20, 18f);//字体宽度 行距 移动宽度 字体大小
            //WordDoc.ActiveWindow.Selection.Font.Bold = 2;
            //WordApp.Selection.ParagraphFormat.LineSpacing = 13f;//设置文档的行间距      
            //object count = 14;//移动焦点并换行 
            //object WdLine = Word.WdUnits.wdLine;//换一行;
            //WordApp.Selection.ParagraphFormat.LineSpacing = 18f;//设置行距
            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //WordApp.Selection.TypeParagraph();//插入段落 
            //WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            //WordApp.Selection.Font.Size = 18f; //设置字体
            //object missing = System.Reflection.Missing.Value;
            //object count2 = 14;
            //object WdLine2 = Word.WdUnits.wdLine;//换一行;
            //  WordApp.Selection.Text = "庭院提升建设验收结算确认书";
            //WordApp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距



            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //   //WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
            // WordApp.Selection.ParagraphFormat.Alignment =Word.WdParagraphAlignment.wdAlignParagraphCenter;
            // WordApp.Selection.TypeParagraph();//插入段落 
            // WordDoc.ActiveWindow.Selection.Font.Bold = 0;
            //  WordApp.Selection.Font.Size = 14f;
            //   WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            //   //WordApp.Selection.Font.Color = Word.WdColor.wdColorBlack;

            //   WordApp.Selection.Text = "关于___________________(项目名称)(合同编号:            ),我司已按合同在约定时间内完成了全部工程量,经双方现场确认,质量合格,符合协议约定标准。现我司申请按合同做如下结算:";

            //   WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //  // WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
            //   WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //   WordApp.Selection.TypeParagraph();//插入段落 
            //   //文档中创建表格 
            //   Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 6, 2, ref Nothing, ref Nothing);
            //   //设置表格样式 
            //   WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 

            //   //设置表格框
            //   newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            //   newTable.Columns[1].Width = 200f;//设置表格列的宽度
            //   newTable.Columns[2].Width = 400f;//设置表格列的宽度


            //  //填充表格内容 
            //  for (int k = 1; k < 6; k++)
            //  {
            //     newTable.Rows[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            //  }
            // for (int k = 1; k < 2; k++)
            //{
            //     newTable.Columns[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            // }
            //  //垂直居中
            // object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            // object countjz = 1;
            // WordApp.Selection.MoveEnd(ref unit, ref countjz);
            //  WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 

            // //填充表格内容 第一行
            //  newTable.Cell(1, 1).Range.Text = "合同内结算金额";
            //  newTable.Cell(2, 1).Range.Text = "签证结算价金额";
            //  newTable.Cell(3, 1).Range.Text = "合计结算总金额";
            //  newTable.Cell(4, 1).Range.Text = "已付预付款金额";
            //  newTable.Cell(5, 1).Range.Text = "质保金";
            //  newTable.Cell(6, 1).Range.Text = "本次应付金额";

            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            // // WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //  WordApp.Selection.TypeParagraph();//插入段落 

            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            //  WordApp.Selection.Font.Size = 12f; //设置字体




            //  WordApp.Selection.Text = "甲方签字或盖章:                                          乙方签字或盖章:";
            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            // // WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
            //  WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //  WordApp.Selection.TypeParagraph();//插入段落 

            //  WordApp.Selection.Text = " 日          期1:                                           日          期:";
        }

        public void darwTable()
        {
            //int lenght = WordDoc.Characters.Count;
            //object start = lenght;
            //object end = lenght;

            表格起始坐标
            //Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end);


            object oStart = "table";
            Word.Range range = WordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置  

            setFontBold(1);
            //WordApp.Selection.Range
            Word.Table newTable = WordDoc.Tables.Add(range, ts.Count + 2 + 1 + 1 + 1, 16, ref Nothing, ref Nothing);//行-列 表头2行 合计两行 总合计一行


            //设置表格样式 
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 

            //设置表格框
            newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            //设置表格列的宽度
            for (int i = 0; i < 16; i++)
            {
                newTable.Columns[i + 1].Width = 35f;
            }

            //    newTable.Columns[1].Width = 200f;//设置表格列的宽度
            //newTable.Columns[2].Width = 350f;//设置表格列的宽度


            //填充表格内容 
            for (int k = 1; k <= ts.Count + 2 + 1 + 1 + 1; k++)
            {
                newTable.Rows[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            }
            for (int k = 1; k <= 16; k++)
            {
                newTable.Columns[k].Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            }
            //垂直居中
            object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            object countjz = 1;
            WordApp.Selection.MoveEnd(ref unit, ref countjz);
            //WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 
            newTable.Select();
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

            //填充表头
            newTable.Cell(1, 1).Range.Text = "清单类型";
            newTable.Cell(1, 1).Merge(newTable.Cell(2, 1));
            newTable.Cell(1, 2).Range.Text = "序号";
            newTable.Cell(1, 2).Merge(newTable.Cell(2, 2));
            newTable.Cell(1, 3).Range.Text = "物料名称";
            newTable.Cell(1, 3).Merge(newTable.Cell(2, 3));
            newTable.Cell(1, 4).Range.Text = "物料编码";
            newTable.Cell(1, 4).Merge(newTable.Cell(2, 4));

            newTable.Cell(1, 5).Range.Text = "规格";
            newTable.Cell(1, 5).Merge(newTable.Cell(1, 9));//合并多列最后一个ID

            newTable.Cell(2, 5).Range.Text = "胸径(cm)";
            newTable.Cell(2, 6).Range.Text = "蓬径(cm)";
            newTable.Cell(2, 7).Range.Text = "高度(cm)";
            newTable.Cell(2, 8).Range.Text = "地径(cm)";
            newTable.Cell(2, 9).Range.Text = "其他要求";

            newTable.Cell(1, 6).Range.Text = "单位";
            newTable.Cell(1, 6).Merge(newTable.Cell(2, 10));

            newTable.Cell(1, 7).Range.Text = "单位";
            newTable.Cell(1, 7).Merge(newTable.Cell(1, 9));//合并多列之后列数重新计算

            newTable.Cell(2, 11).Range.Text = "合同数量";
            newTable.Cell(2, 12).Range.Text = "变更数量";
            newTable.Cell(2, 13).Range.Text = "结算数量";

            newTable.Cell(1, 8).Range.Text = "合同单价";
            newTable.Cell(1, 8).Merge(newTable.Cell(2, 14));
            newTable.Cell(1, 9).Range.Text = "合价";
            newTable.Cell(1, 9).Merge(newTable.Cell(2, 15));
            newTable.Cell(1, 10).Range.Text = "备注";
            newTable.Cell(1, 10).Merge(newTable.Cell(2, 16));

            newTable.Rows.Select();
            setFontBold(0);
            //设置单元格风格:
            Word.Range rngCell = null;
            for (int i = 1; i <= 10; i++)
            {
                rngCell = newTable.Cell(1, i).Range;
                rngCell.Font.Bold = 1;
                rngCell.Font.Name = "宋体";
            }
            for (int i = 5; i <= 9; i++)
            {
                rngCell = newTable.Cell(2, i).Range;
                rngCell.Font.Bold = 1;
                rngCell.Font.Name = "宋体";
            }
            for (int i = 11; i <= 13; i++)
            {
                rngCell = newTable.Cell(2, i).Range;
                rngCell.Font.Bold = 1;
                rngCell.Font.Name = "宋体";
            }

            int htCount = ts.Count(a => a.OrderType == 1);
            int xzCount = ts.Count(a => a.OrderType == 2);
            int row = 0;

            //添加物料行
            for (int i = 0; i < ts.Count; i++)
            {

                if (i >= htCount)
                {
                    row = i + 4;//第三行+1
                }
                else
                {
                    row = i + 3;//第三行
                }
                //if (ts[i].OrderType == 1)
                //{
                //    htCount++;
                //}
                //else if (ts[i].OrderType == 2)
                //{

                //    xzCount++;
                //}
                newTable.Cell(row, 2).Range.Text = (i + 1).ToString();
                newTable.Cell(row, 3).Range.Text = ts[i].SPName;
                newTable.Cell(row, 4).Range.Text = ts[i].SuppliesNumber;
                newTable.Cell(row, 5).Range.Text = ts[i].NC;
                newTable.Cell(row, 6).Range.Text = ts[i].NP;
                newTable.Cell(row, 7).Range.Text = ts[i].NH;
                newTable.Cell(row, 8).Range.Text = ts[i].NF;
                newTable.Cell(row, 9).Range.Text = ts[i].Remark;
                newTable.Cell(row, 10).Range.Text = ts[i].Unit;
                newTable.Cell(row, 11).Range.Text = ts[i].Num.ToString();
                newTable.Cell(row, 12).Range.Text = ts[i].BGNum.ToString();
                newTable.Cell(row, 13).Range.Text = ts[i].JSNum.ToString();
                newTable.Cell(row, 14).Range.Text = ts[i].ContractPrice.ToString();
                newTable.Cell(row, 15).Range.Text = ts[i].TotalContractPrice.ToString();
                newTable.Cell(row, 16).Range.Text = ts[i].ProjectRemark;
                
                if (ts[i].OrderType == 1)
                {
                    htPriceSum += ts[i].TotalContractPrice;
                }
                else if (ts[i].OrderType == 2)
                {
                    xzPriceSum += ts[i].TotalContractPrice;
                }

            }
            newTable.Cell(3, 1).Range.Text = "合同清单";
            newTable.Cell(3, 1).Merge(newTable.Cell(3 + htCount, 1));
            newTable.Cell(4 + htCount, 1).Range.Text = "新增品种清单";
            newTable.Cell(4 + htCount, 1).Merge(newTable.Cell(4 + ts.Count, 1));


            //合同清单合计行
            newTable.Cell(3 + htCount, 2).Range.Text = "合计";
            newTable.Cell(3 + htCount, 2).Merge(newTable.Cell(3 + htCount, 9));
            newTable.Cell(3 + htCount, 3).Range.Text = htPriceSum.ToString();
            newTable.Cell(3 + htCount, 3).Merge(newTable.Cell(3 + htCount, 9));
            //新增合计行
            newTable.Cell(4 + ts.Count, 2).Range.Text = "合计";
            newTable.Cell(4 + ts.Count, 2).Merge(newTable.Cell(4 + ts.Count, 9));
            newTable.Cell(4 + ts.Count, 3).Range.Text = xzPriceSum.ToString();
            newTable.Cell(4 + ts.Count, 3).Merge(newTable.Cell(4 + ts.Count, 9));
            //总合计
            newTable.Cell(5 + ts.Count, 1).Range.Text = "景观工程总造价";
            newTable.Cell(5 + ts.Count, 1).Merge(newTable.Cell(5 + ts.Count, 4));
            newTable.Cell(5 + ts.Count, 2).Range.Text = "大写";

            EcanRMB rmb = new EcanRMB();
            newTable.Cell(5 + ts.Count, 3).Range.Text = rmb.CmycurD((htPriceSum + xzPriceSum).ToString());
            newTable.Cell(5 + ts.Count, 3).Merge(newTable.Cell(5 + ts.Count, 9));

            newTable.Cell(5 + ts.Count, 4).Range.Text = "小写";

            newTable.Cell(5 + ts.Count, 5).Range.Text = (htPriceSum + xzPriceSum).ToString();
            newTable.Cell(5 + ts.Count, 5).Merge(newTable.Cell(5 + ts.Count, 7));
            exitSave();
        }

        //替换字段
        public void tihuan(Dictionary<string, string> datas)
        {

            WordApp = new Word.Application();//创建word应用程序
            //object fileName = Server.MapPath(filename.ToString());//模板文件
            //打开模板文件
            object oMissing = System.Reflection.Missing.Value;
            WordDoc = WordApp.Documents.Open(ref filename,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            object replace = Word.WdReplace.wdReplaceAll;
            foreach (var item in datas)
            {
                WordApp.Selection.Find.Replacement.ClearFormatting();
                WordApp.Selection.Find.ClearFormatting();
                WordApp.Selection.Find.Text = item.Key;//需要被替换的文本
                WordApp.Selection.Find.Replacement.Text = item.Value;//替换文本 

                //执行替换操作
                WordApp.Selection.Find.Execute(
                ref oMissing, ref oMissing,
                ref oMissing, ref oMissing,
                ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref replace,
                ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);
            }
            exitSave();
        }
        protected void killAllProcess() // 杀掉所有winword.exe进程 
        {
            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
                    {
                    }
                }
            }

        }
        /// <summary>
        /// 设置文档格式
        /// </summary>
        /// <param name="WordApp"></param>
        /// <param name="WordDoc"></param>
        /// <param name="Nothing"></param>
        /// <param name="FontBold">字体宽度</param>
        /// <param name="LinesSpancing">行距</param>
        /// <param name="MoveWith">光标移动宽度</param>
        /// <param name="FontSize">字体大小</param>(2,18f,14,18f)
        //private void setStyte(Word.Application WordApp, Word.Document WordDoc, object Nothing,int FontBold,float LinesSpancing,int MoveWith,float FontSize)
        //{
        //    WordDoc.ActiveWindow.Selection.Font.Bold = FontBold;
        //    object count = MoveWith;//移动宽度
        //    object WdLine = Word.WdUnits.wdLine;//换一行;
        //    WordApp.Selection.ParagraphFormat.LineSpacing = LinesSpancing;//设置行距
        //    WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //    WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //    WordApp.Selection.TypeParagraph();//插入段落 
        //    WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 并换行
        //    WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
        //    WordApp.Selection.Font.Size = FontSize; //设置字体
        //   // WordApp.Selection.Font.Color = Word.WdColor.wdColorBlack;//设置字体颜色
        //}
        /// <summary>
        /// 设置粗体
        /// </summary>
        /// <param name="Bold"></param>
        public void setFontBold(int Bold)
        {
            WordDoc.ActiveWindow.Selection.Font.Bold = Bold;
        }
        /// <summary>
        /// 设置行距
        /// </summary>
        /// <param name="LineSpacing"></param>
        public void setLineSpacing(float LineSpacing)
        {
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordApp.Selection.ParagraphFormat.LineSpacing = LineSpacing;
        }
        /// <summary>
        /// 设置单倍行距
        /// </summary>
        public void setLineSpaceSingle()
        {
            WordApp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
        }
        public void Move(Object count)
        {
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            // WordApp.Selection.MoveDown(ref count, ref Nothing);//移动焦点 
            WordApp.Selection.Move(ref count, ref Nothing);
        }
        //移动光标
        public void setLineCount(object count)
        {
            object WdLine = Word.WdUnits.wdLine;//换一行;
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 
        }
        /// <summary>
        /// 设置字体大小
        /// </summary>
        /// <param name="Size"></param>
        public void setFontSize(float Size)
        {
            WordApp.Selection.Font.Size = Size;
        }
        /// <summary>
        /// 设置字体
        /// </summary>
        /// <param name="str"></param>
        public void setFontName(string str)
        {
            WordApp.Selection.Font.Name = str;
        }
        /// <summary>
        /// 插入段落
        /// </summary>
        public void chaRuDuLuo()
        {
            WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordApp.Selection.TypeParagraph();//插入段落 
        }
        /// <summary>
        /// 写入文本
        /// </summary>
        /// <param name="str"></param>
        public void setText(string str)
        {
            WordApp.Selection.Text = str;
        }
        /// <summary>
        /// 回车换行
        /// </summary>
        public void checkLine()
        {
            WordDoc.Content.InsertAfter("\n");
        }
        /// <summary>
        /// 将光标移至文末
        /// </summary>
        public void endKey()
        {
            WordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移至文末
        }
        /// <summary>
        /// 回车换行
        /// </summary>
        public void InsertLineBreak()
        {
            WordApp.Selection.TypeParagraph();
        }


        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
代码比较乱也没有整理




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值