77 lines
2.5 KiB
C#

using System.Runtime.InteropServices;
using System.Windows.Forms;
using System;
using Word = Microsoft.Office.Interop.Word;
using System.Collections.Generic;
namespace AIProofread.core
{
public class ProcessingContext
{
public Word.Range Range { get; set; }
public int GlobalIndex { get; set; }
}
public class DocumentReader
{
private static readonly Stack<ProcessingContext> _processingStack = new Stack<ProcessingContext>();
public static List<DocumentText> ReadByVSTO(Word.Document _doc, Word.Application _app, List<DocumentText> list)
{
//List<DocumentText> list = new List<DocumentText>();
try
{
// 关闭屏幕更新
_app.ScreenUpdating = false;
// 初始化堆栈:处理所有顶级 StoryRanges
foreach (Word.Range storyRange in _doc.StoryRanges)
{
_processingStack.Push(new ProcessingContext
{
Range = storyRange,
GlobalIndex = 0,
});
}
// 迭代处理堆栈中的每个 Range
while (_processingStack.Count > 0)
{
var context = _processingStack.Pop();
ProcessElement(context.Range, context.GlobalIndex, list);
Marshal.ReleaseComObject(context.Range);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
_app.ScreenUpdating = true;
Marshal.ReleaseComObject(_doc);
}
return list;
}
private static void ProcessElement(Word.Range range, int globalIndex, List<DocumentText> list)
{
if (range.Text?.Trim() == "\r\a")
{
globalIndex++;
return;
}
var paragraphs = range.Paragraphs;
// Debug.WriteLine($"Processing element: {range.Text}");
// 处理段落
foreach (Word.Paragraph paragraph in paragraphs)
{
list.Add(new DocumentText
{
Text = paragraph.Range.Text,
ParagraphNumber = globalIndex + 1
});
Marshal.ReleaseComObject(paragraph);
globalIndex++;
}
}
}
}