Невозможно удалить пустую страницу из документа Word с помощью пакета C # Microsoft.Office.Interop.Word - PullRequest
0 голосов
/ 21 апреля 2019

В Visual Studio 2017 C # 4.0 я пытался удалить пустую страницу из документа Word с помощью пакета C # Microsoft.Office.Interop.Word. Я пробовал разные методы, но все как-то не получалось.

Я применил следующие методы для удаления пустой страницы:

1) Удалить соответствующий абзац пустой страницы, используя метод Word.Range.Delete (Word.Paragraph); 2) Удалить полностью пустую страницу с помощью метода Word.Paragraph.Range.Delete (); 3) Удалите пустую страницу, непрерывно вводя клавиши возврата;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using System.Drawing;
using System.Diagnostics;

using System.Timers;
using System.Windows.Forms;

using Process = System.Diagnostics.Process;
using System.Collections;

namespace getWordPages
{
    public partial class Form1 : Form
    {
        Word.Application WordApplication;
        Word._Document Doc;

        public Form1()
        {
            InitializeComponent();
        }

        ~Form1()
        {
            if (Doc != null)
                Doc.Close(0);

            if (WordApplication != null)
                WordApplication.Quit();

            Doc = null;
            WordApplication = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string filename = tbWordDoc.Text;
            string[] Pages = GetPagesDoc(filename);
            tbPageNo.Text = tbPageNo.Text.Trim();
            int iPageNum = Convert.ToInt32(tbPageNo.Text);
            tbPageContent.Text = Pages[iPageNum-1];
        }

        private bool emptyText(string text, ref int nLines)
        {
            bool res = true;
            nLines = 0;
            foreach( char ch in text)
            {
                if ((ch >= ' ') && (ch <= 127))
                    res = true;
                else
                    nLines++;
            }
            return (res);
        }

        private bool isBlankPage(Word.Range range, ref int nLines)
        {
            if (range.Bookmarks.Count > 0)
                return false;
            if( range.FormFields.Count > 0 )
                return false;
            if (range.Frames.Count > 0)
                return false;
            if (range.Hyperlinks.Count>0)
                return false;
            if (range.InlineShapes.Count > 0)
                return false;
            if (range.ShapeRange.Count > 0)
                return false;
            if (range.Tables.Count > 0)
                return false;
            if (!emptyText(range.Text, ref nLines))
                return false;
            return (true);
        }

        public string[] GetPagesDoc(object Path)
        {
            List<string> Pages = new List<string>();

            // Get application object
            WordApplication = new Word.Application();
            WordApplication.Visible = true;
            // WordApplication.Visible = false;

            // Get document object
            object Miss = System.Reflection.Missing.Value;
            object ReadOnly = false;
            object Visible = true;
            Doc = WordApplication.Documents.Open(ref Path, ref Miss, ref ReadOnly, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Visible, ref Miss, ref Miss, ref Miss, ref Miss);

            // Get pages count
            Word.WdStatistic PagesCountStat = Word.WdStatistic.wdStatisticPages;
            int PagesCount = Doc.ComputeStatistics(PagesCountStat, ref Miss);

            Doc.Activate();

            //Get pages
            object What = Word.WdGoToItem.wdGoToPage;
            object Which = Word.WdGoToDirection.wdGoToAbsolute;
            object Start;
            object End;
            object CurrentPageNumber;
            object NextPageNumber;

            Word.Range wordRange;
            int nLines = 0;

            for (int Index = 1; Index <= PagesCount; Index++)
            {
                CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                NextPageNumber = (Convert.ToInt32((Index + 1).ToString()));

                // Get start position of current page
                Start = WordApplication.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;

                // Get end position of current page                                
                End = WordApplication.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;

                // Get text
                if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
                {
                    wordRange = Doc.Range(ref Start, ref End);
                    Pages.Add(wordRange.Text);
                }
                else
                {
                    wordRange = Doc.Range(ref Start);
                    Pages.Add(wordRange.Text);
                }
                if( Index == 2 )
                {
                    int bookmark_cnt = wordRange.Bookmarks.Count;
                    int formfield_cnt = wordRange.FormFields.Count;
                    int frame_cnt = wordRange.Frames.Count;
                    int hyperlink_cnt = wordRange.Hyperlinks.Count;
                    int table_cnt = wordRange.Tables.Count;
                    int inlineshape_cnt = wordRange.InlineShapes.Count;
                    int shaperange_cnt = wordRange.ShapeRange.Count;
                    int paragraph_cnt = wordRange.Paragraphs.Count;
                    int section_cnt = wordRange.Sections.Count;
                    int sentence_cnt = wordRange.Sentences.Count;
                }
                if (isBlankPage(wordRange, ref nLines))
                    deletePageByBackspace(wordRange, 2*nLines);
            }
            // deleteBetweenBookmarks("Start_Bookmark", "End_Bookmark");
            return Pages.ToArray<string>();
        }

        private void deleteBetweenBookmarks(string startBookmark, string endBookmark)
        {
            Word.Range range = Doc.Range();
            range.Start = Doc.Bookmarks.get_Item(startBookmark).Range.Start;
            range.End = Doc.Bookmarks.get_Item(endBookmark).Range.End;
            range.Delete();
        }

        private void deletePage(Word.Range range, int nLines)
        {
            string newline = "\r";
            foreach (Word.Paragraph para in range.Paragraphs)
            {
                if (para.ToString().Contains(newline))
                {
                    para.Range.Select();
                    range.Delete(para);
                }
            }
        }

        private void deleteFullPage(Word.Range range)
        {
            foreach (Word.Paragraph para in range.Paragraphs)
            {
                para.Range.Select();
                para.Range.Delete();
            }
        }

        private void deletePageByBackspace(Word.Range range, int nLines)
        {
            object oMissing = System.Reflection.Missing.Value;
            object what = Word.WdGoToItem.wdGoToPercent;
            object which = Word.WdGoToDirection.wdGoToLast;

            range.Select();
            // range.Delete(Type.Missing);
            for (int i = 0; i < nLines; i++)
                WordApplication.Selection.TypeBackspace();
        }


        public static void KillProcesses(string processName)
        {
            Process[] _allProcesses = Process.GetProcessesByName(processName);

            // check to kill the right process
            foreach (Process currentProcess in _allProcesses)
            {
                currentProcess.Kill();
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
    }
}

Ожидаемый результат: пустая страница в образце документа Word будет удалена. Фактический результат: пустая страница все еще там после запуска моей вышеупомянутой проблемы.

Кстати, я задал еще один вопрос: есть ли кто-нибудь, кто знает, как я могу загрузить образец документа Word в этот форум переполнения стека?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...