天天看点

C#打开word进行操作,文字替换、书签处插入图片、读取文档中的表格、修改表格数据

C#打开word进行操作,文字替换、书签处插入图片、读取文档中的表格、修改表格数据

public class WordHelp
    {
        private string _JpgsPath = string.Format("{0}\\Jpgs\\", CommenPara.STR_TempPath);

        public void OpenWord(string templateFile, object saveFile, ReportInfo reprortInfo,
            GD.COM.TechReview.CoClass.LandCheckTypeConfig m_ConfigType)
        {

            Application wordApp =null ;       //声明word应用程序变量  
            Document m_Doc = null ;          //声明word文档变量    
            object Nothing = Missing.Value;                              //表示缺少的值  
            object format = WdSaveFormat.wdFormatDocumentDefault; //格式docx 
            try
            {

                wordApp = new ApplicationClass();                     //声明一个wordAPP对象  
                System.IO.File.Copy(templateFile,saveFile.ToString(),true);//将模板文件复制为目标文件
                //worddoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                object nullobj = Type.Missing;

                object file = saveFile;
                //打开目标word文件进行操作
                m_Doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj);
                #region  替换掉 文档中的某些特定文字                
                WordReplace(wordApp,m_Doc, "_ProjectName", reprortInfo.ProjectName);
                WordReplace(wordApp, m_Doc, "ProjectTime", DateTime.Now.ToString("yyyy-MM-dd"));
                #endregion

                Table tableTemp;//储存当前文档的表格
                Row tRow;
                ComplianceType complianceType;
                List<string> tempStrList = new List<string>();

                //找到doc中所有的表
                List<Table> tableList = new List<Table>();
                foreach (Table tbItem in m_Doc.Tables)
                {
                    tableList.Add(tbItem);
                }



                complianceType = landTypeList.FirstOrDefault(s => s.TypeName == "适建区");
                if (complianceType != null)
                    PlanArea = complianceType.TotalArea;               

                InsertImageAtBookmark(m_Doc, "三区图", _JpgsPath + "三区图.jpg");

                #region 生态廊道

                tableTemp = tableList[20];
                InsertImageAtBookmark(m_Doc , "生态廊道1", _JpgsPath + complianceType.IllustrationList[0]);
                    for (int i = 0; i < tableTemp.Columns.Count; i++)
                    {
                        tableTemp.Cell(tableTemp.Rows.Count, i + 1).Range.Text = tempStrList[i];
                    }
                    

                #endregion

                foreach(var table in tableList)
                {
                    table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//居中
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if(m_Doc!=null&& wordApp!=null)
                {
                    m_Doc.Save();
                    m_Doc.Close(ref Nothing, ref Nothing, ref Nothing);  //关闭worddoc文档对象  
                    wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);   //关闭wordApp组对象  
                                                                           MessageBox.Show("");
                                                                           ///
                    WaitFormService.CloseWaitForm();
                }
            }
        }
        /// <summary>
        /// 在文档的书签位置插入图片
        /// </summary>
        /// <param name="m_Doc">文档</param>
        /// <param name="bookMarkName">书签名称(在word设置好的)</param>
        /// <param name="imagePath">图片文件全路径</param>

        private void InsertImageAtBookmark(Document m_Doc,string bookMarkName,string imagePath)
        {
            object bk = bookMarkName;
            if (m_Doc.Bookmarks.Exists(bookMarkName))
            {
                Range range = m_Doc.Bookmarks.get_Item(ref bk).Range;//.Text = "insert text"; // 插入文本
                range.Text = "";

                object rangeo = range;
                object linktofile = false;
                object savedocument = true;
                if (System.IO.File.Exists(imagePath))
                {
                    InlineShape inlineShape= m_Doc.InlineShapes.AddPicture(imagePath, ref linktofile, ref savedocument, ref rangeo);
                    inlineShape.Width = (float)(28.345 * 14.86);//图片宽度   
                    inlineShape.Height = (float)(28.345 * 10.64);//图片高度  
                    inlineShape.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;                 
                    Range ran = m_Doc.Range(range.End+1 , range.End+1);
                    ran.Text = "\n" + bookMarkName + "示意图\n";
                    ran.FormattedText.Font.Name = "仿宋_GB2312";
                    ran.FormattedText.Font.Size = 12;
                    ran.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//居中
                }


            }
           
        }
     
        /// <summary>
        /// 替换表格中的文字
        /// </summary>
        private void ReplaceTableCellText(Row tr, int cellIndex, string s)
        {
            Cell tc = tr.Cells[cellIndex];
            tc.Range.Text = s;
        }

        /// <summary>
        /// 替换全局文档文字
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strOld"></param>
        /// <param name="strNew"></param>
        private void WordReplace(string filePath, string strOld, string strNew)
        {

            Microsoft.Office.Interop.Word._Application app = new Microsoft.Office.Interop.Word.ApplicationClass();//new Microsoft.Office.Interop.Word.ApplicationClass();

            object nullobj = Type.Missing;

            object file = filePath;

            Microsoft.Office.Interop.Word._Document doc = app.Documents.Open(
            ref file, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj, ref nullobj) as Microsoft.Office.Interop.Word._Document;

            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            app.Selection.Find.Text = strOld;
            app.Selection.Find.Replacement.Text = strNew;

            object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

            app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref objReplace, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj);


            //清空Range对象
            //Microsoft.Office.Interop.Word.Range range = null;

            //保存
            doc.Save();
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            app.Quit(ref nullobj, ref nullobj, ref nullobj);
        }
        /// <summary>
        /// 替换文字
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strOld"></param>
        /// <param name="strNew"></param>
        public void WordReplace(_Application app,_Document doc, string strOld, string strNew)
        {
            object nullobj = Type.Missing;
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            app.Selection.Find.Text = strOld;
            app.Selection.Find.Replacement.Text = strNew;
            object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
            app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref objReplace, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj);
        }
       
        /// <summary>
        /// 设置文档中表格的单元格文字的内容、字体大小、居中等属性
        /// </summary>
        /// <param name="table"></param>
        /// <param name="hang"></param>
        /// <param name="lie"></param>
        /// <param name="width"></param>
        /// <param name="value"></param>
        public void cellsGet(Table table, int hang, int lie, int width, string value)
        {
            table.Cell(hang, lie).Range.Text = value;
            table.Cell(hang, lie).Range.Bold = 0;
            table.Cell(hang, lie).Range.Font.Name = "仿宋";
            table.Cell(hang, lie).Range.Font.Size = 14;
            table.Cell(hang, lie).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            table.Cell(hang, lie).Width = width;
        }
        /// <summary>
        /// 填充表格内容
        /// </summary>
        /// <param name="complianceType"></param>
        /// <param name="tableTemp"></param>
        private void FillLandTypeTable2(ComplianceType complianceType, Table tableTemp)
        {
            if (complianceType != null)
            {
                Row tRow;
                Object Nothing = System.Reflection.Missing.Value;
                double landTotalArea = 0;
                for (int i = 0; i < complianceType.LandInfoList.Count; i++)
                {
                    LandInfo landInfo = complianceType.LandInfoList[i];
         
                        ReplaceTableCellText(tRow,1, landInfo.LandCode);
                    
                }
                tRow = tableTemp.Rows.Last;         

                ReplaceTableCellText(tRow, 8, (complianceType.TotalArea / PlanArea * 100).ToString("0.00") + "%(占比合计)");

            }
        }
    }