前言:本人是java开发,项目需要读取到页码。在网上找了很久很久很久,终于找到了一个叫Microsoft.Office.Interop.Word的东西。
简单来说就是 Microsoft 提供的官方处理word的接口,编程语言是c#
官方文档:https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.office.interop.word?redirectedfrom=MSDN&view=word-pia
- 核心代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.IO;
namespace Invoke
{
public class Method
{
public string getString(string @filePath)
{
// 代码对齐 ctrl+K ctrl+F
// 注释 先ctrl+K 后ctrl+C
// 取消注释 先ctrl+K 后ctrl+U
// Application 代表 Word应用程序
Application application = new Application();
// 默认false,打开word程序时,不弹出word文件显示
// application.Visible = false;
// word文档
Document document = null;
Object path = @filePath;
// 参数 (缺省)
object missing = Missing.Value;
// WdGoToItem 枚举 项目类型
object objWhat = WdGoToItem.wdGoToPage;
// WdGoToDirection 枚举 位置
object objWhich = WdGoToDirection.wdGoToNext;
// 页号
object page = null;
StringBuilder pageStr = new StringBuilder();
// 因为 c# c++ java 集合转换的复杂性,ArrayList 改成 StringBuilder
// ArrayList pageList = new ArrayList();
try
{
document = application.Documents.Open(ref path);
// 文档内容
// string text = document.Content.Text;
// 总页数
int filePages = document.ComputeStatistics(WdStatistic.wdStatisticPages);
for (int i = 0; i < filePages; i++)
{
page = i;
// Range 文档中的一个连续区域
Range range1 = document.GoTo(ref objWhat, ref objWhich, ref page);
Range range2 = range1.GoToNext(WdGoToItem.wdGoToPage);
// Range.Start 返回或设置范围的起始字符位置
object objStart = range1.Start;
object objEnd = range2.Start;
// 最后一页
if (range1.Start == range2.Start)
{
objEnd = missing;
}
// Document.Range 使用指定的起始和结束字符位置返回一个对象
Range range3 = document.Range(ref objStart, ref objEnd);
// Range.Text 返回或设置指定区域的文本
string content = range3.Text;
// Hashtable 键值对
// Hashtable hashtable = new Hashtable();
// hashtable.Add("currPage", i + 1);
// hashtable.Add("content", content);
// pageList.Add(hashtable);
pageStr.Append(content);
pageStr.Append("<!--PageBreak-->");
}
// 等待按键并读取
// Console.ReadKey();
return pageStr.ToString();
}
catch (Exception)
{
return "DOC_READ_ERROR";
}
finally
{
// 关闭通道,清空内存
if (document != null)
{
document.Close();
}
application.Quit();
}
}
}
}
要引入相应的命名空间,才可以using
- 碎碎念
项目开发时用的是Java,开发一半了,发现poi读不到页码。找了很久很久很久,只找到了c#的方法,所以java调用c#的时候又用到了jna技术。
打工不易,小农叹气~~~