天天看點

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") + "%(占比合計)");

            }
        }
    }