使用C#Microsoft.Office.Interop.Word程序包无法从Word文档中删除空白页

时间:2019-04-21 10:39:23

标签: c#-4.0

在Visual Studio 2017 C#4.0下,我试图使用C#Microsoft.Office.Interop.Word包从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文档上载到这个Stack Overflow论坛中?

0 个答案:

没有答案