1. 程式人生 > 其它 >C#開啟word進行操作,文字替換、書籤處插入圖片、讀取文件中的表格、修改表格資料

C#開啟word進行操作,文字替換、書籤處插入圖片、讀取文件中的表格、修改表格資料

技術標籤:C#Word操作c#

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

            }
        }
    }