使用C#以编程方式编辑大型Word文档

时间:2018-09-19 07:40:24

标签: c# visual-c#-express-2010

我正在尝试以编程方式将某些字段从一个大的word文档文件复制到另一个文件中。 要复制的文件已从pdf图像文件转换为word。它具有以下格式:

Construction Log

要复制到的单词模板具有以下格式:

Supervision Log

我的代码可以将施工日志第一页的数据正确粘贴到监督日志中,而不能复制粘贴第二到第三页的数据……

这是我的代码:

       using System;
        using System.Windows.Forms;
        using Word = Microsoft.Office.Interop.Word;

        namespace LogConverter
        {
            class Program
            {
                static void Main()
                {
                    try
                    {
                        var fileName = Application.StartupPath + @"\Construction Logs.docx";

                        var wordApp = new Word.Application();
                        wordApp.Visible = true;
                        var document = wordApp.Documents.Open(fileName);

                        string filePath = Application.StartupPath + @"\Supervision Logs.dotx";
                        Word.Application LogApp = new Word.Application();
                        Word.Document wordDoc = wordApp.Documents.Add(filePath);
                        object oMissing = System.Reflection.Missing.Value;
                        wordApp.Visible = true;
                        Word.Selection selection = wordApp.Selection;

                        Word.Range rangeDoc = wordDoc.Range();

                        int PageCnt = 1;
                        SearchPerPage(wordDoc, oMissing, selection, rangeDoc, document, PageCnt);
                        PageCnt++;

                        wordApp.Documents.Close();
                        LogApp.Documents.Close();
                        wordApp.Quit();
                        LogApp.Quit();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.InnerException);
                        Console.ReadKey();
                    }            
                }

                static void SearchPerPage(Word.Document wordDoc, object oMissing, Word.Selection selection, Word.Range rangeDoc, Word.Document document, int pageCnt)
                {
                    foreach (Word.Range storyRange in document.StoryRanges)
                    {
                        var range = storyRange;
// I have changed the while loop to loop till end of the document i.e last paragraph
                           while (range != null && 
 range!=document.Paragraphs.Last)
                        {
                            //Get string between two strings in a string
                            String St = storyRange.Text;

                            if (!St.Contains("Date")) continue;

                            //Get Date portion of record
                            int DateFrom = St.IndexOf("Date:") + "Date:".Length;
                            int DateTo = St.IndexOf("Weather:");
                            string Date = St.Substring(DateFrom, DateTo - DateFrom);

                            //Get Temperature portion of record
                            int TempFrom = St.IndexOf("Temperature:") + "Temperature:".Length;
                            int TempTo = St.IndexOf("I .Construction");
                            string Temperature = St.Substring(TempFrom, TempTo - TempFrom);

                            //Get Construction work portion of record
                            int ConsFrom = St.IndexOf("Construction Work") + "Construction Work".Length;
                            int ConsTo = St.IndexOf("II. Construction");
                            string Construction = St.Substring(ConsFrom, ConsTo - ConsFrom);

                            //Get Construction machinery portion of record
                            int MachFrom = St.IndexOf("Construction Equipment and Machinery") + "Construction Equipment and Machinery".Length;
                            int MachTo = St.IndexOf("Construction Materials\r");
                            string Machinery = St.Substring(MachFrom, MachTo - MachFrom);

                            //Get Construction personnel portion of record
                            int PersFrom = St.IndexOf("Construction Personnel") + "Construction Personnel".Length;
                            int PersTo = St.IndexOf("Construction Equipment and Machinery");
                            string Personnel = St.Substring(PersFrom, PersTo - PersFrom);

                            //Get Quality inspection portion of record
                            int QCFrom = St.IndexOf("Quality Inspection") + "Quality Inspection".Length;
                            int QCTo = St.IndexOf("Constructional Safety");
                            string Quality = St.Substring(QCFrom, QCTo - QCFrom);

                            //Get Safety inspection portion of record
                            int SafeFrom = St.IndexOf("Constructional Safety") + "Constructional Safety".Length;
                            int SafeTo = St.IndexOf("and no phenomenon of improper operations.");
                            string Safety = St.Substring(SafeFrom, SafeTo - SafeFrom);

                            //Write the Supervision Log
                            LogWriter(wordDoc, oMissing, selection, rangeDoc, pageCnt, Date, Temperature, Construction, Machinery, Personnel, Quality, Safety);

                            //if (range.ShapeRange.Count > 0)
                            //{
                            //    foreach (Word.Shape shape in range.ShapeRange)
                            //    {
                            //        if (shape.TextFrame.HasText != 0)
                            //        {
                            //            LogWriter(wordDoc, oMissing, selection, rangeDoc, pageCnt, Date, Temperature, Construction, Machinery, Personnel, Quality, Safety);
                            //        }
                            //    }
                            //}
                            range = range.NextStoryRange;
                        }
                    }
                }

                static void LogWriter(Word.Document wordDoc, object oMissing, Word.Selection selection, Word.Range rangeDoc, int pageCnt, string Date, string Temperature, string Construction, string Machinery, string Personnel, string Quality, string Safety)
                {
                    //Copy the template page
                    wordDoc.Bookmarks[@"\Page"].Range.Copy();

                    //inserting a page break: first go to end of document
                    selection.EndKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove);

                    //insert a page break
                    object breakType = Word.WdBreakType.wdPageBreak;
                    selection.InsertBreak(ref breakType);

                    //Replace the text in the correct fields.
                    rangeDoc.Find.Execute(FindText: "{{Date}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Date);
                    rangeDoc.Find.Execute(FindText: "{{TemperatureRecord}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Temperature.Replace("\r",""));
                    rangeDoc.Find.Execute(FindText: "{{ConstructionWork}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Construction.Replace("\r", ""));
                    rangeDoc.Find.Execute(FindText: "{{ConstructionMachinery}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Machinery.Replace("\r", ""));
                    rangeDoc.Find.Execute(FindText: "{{ConstructionPersonnel}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Personnel.Replace("\r", ""));
                    //rangeDoc.Find.Execute(FindText: "{{QualityInspection}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Quality.Replace("\r", ""));
                    rangeDoc.Find.Execute(FindText: "{{SafetyInspection}}", Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: Safety.Replace("\r", ""));

                    rangeDoc.Find.Execute("{{QualityInspection}}");
                    rangeDoc.Text = Quality.Replace("\r", "");

                    //Paste the template page onto a new one
                    selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);                      
                }
            }
        }

任何人都可以协助修复以读取其他施工日志页面并将其正确粘贴吗?

1 个答案:

答案 0 :(得分:1)

you can insert below code to retrieve number of pages and call your function for all pages instead of one page

 Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                int numpages = document.ComputeStatistics(stat, ref oMissing);

                int PageCnt = 1;
                while (PageCnt < numpages)
                {
                    SearchPerPage(wordDoc, oMissing, selection, rangeDoc, document, PageCnt);
                    PageCnt++;
                }