我有这段代码:
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
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);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();
textBox2.Text = text;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);
但它不会返回页码。如何获取页码?
答案 0 :(得分:6)
我认为这是一个更好的解决方案
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
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);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
// get number of pages
Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
int pages = doc.ComputeStatistics(stat, Type.Missing);
string text = data.GetData(DataFormats.Text).ToString();
textBox2.Text = text;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);
答案 1 :(得分:1)
看看这个例子:
具体来说,请查看Word.WdFieldType.wdFieldPage
和Word.WdFieldType.wdFieldNumPages
。
答案 2 :(得分:0)
对我来说,ComputeStatistics函数会给我一个比实际页数更高的数字,这对我来说并不起作用。
我使用了range.get_Information()
var range = doc.Range().GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToLast);
var numPages = range.get_Information(WdInformation.wdActiveEndPageNumber);
第一行获取文档最后一页的范围。 第二行获取范围所在的页面。