1. 程式人生 > >C# 刪除word的指定頁

C# 刪除word的指定頁

using Microsoft.Office.Interop.Word;
 

//啟動Word程式
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
object oMissing = System.Reflection.Missing.Value;
object filePath = ""; //這裡是Word檔案的路徑
//開啟檔案
Document wordDoc = wordApp.Documents.Open(
ref filePath, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//下面是取得開啟檔案的頁數
int pages = wordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMissing);

 

 object objWhat = Word.WdGoToItem.wdGoToPage

 object objWhich = Word.WdGoToDirection.wdGoToAbsolute;

 object objPage = 2;//指定頁

 Word.Range range1 = wordDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref oMissing);

 Word.Range range2 = range1.GoToNext(Word.WdGoToItem.wdGoToPage);

 

 object objStart = range1.Start;

 object objEnd = range2.Start;

 if (range1.Start == range2.Start)
     objEnd = wordDoc.Characters.Count;//最後一頁

 

 string str=wordDoc.Range(ref objStart, ref objEnd).Text;

 MessageBox.Show(str);

 if(string.IsNullOrEmpty(str.Trim()))

{

            object Unit = (int)Word.WdUnits.wdCharacter;
            object Count = 1;
            wordDoc.Range(ref bjStart, ref  objEnd).Delete(ref  Unit, ref  Count);

}

 

wordDoc.Save();


//關閉檔案
wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//退出Word程式
wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);