在 C# 中使用 aspose.words 从 word 文档中提取项目符号

问题描述

我需要从 C# 中的 word 文档中提取带有项目符号样式的文本。我正在使用 aspose.words 库,但也欢迎使用不同库的解决方案。我已经可以上传文档并使用 Heading1 样式提取文本。但是当我尝试使用子弹样式时,我一无所获。

我正在使用下面的代码来获取带有 Heading1 样式的文本并且有效。

var heading1 = doc
    .GetChildNodes(NodeType.Paragraph,true)
    .Cast<Aspose.Words.Paragraph>()
    .ToArray()
    .Where(p => p.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading1);
    
foreach (var head1 in heading1)
{
    listBox11.Items.Add(head1.gettext()tostring());
}

我正在尝试使用下面的代码来获取带有项目符号样式的文本,但这不起作用。

var bullets = doc
    .GetChildNodes(NodeType.Paragraph,true)
    .Cast<Aspose.Words.Paragraph>()
    .ToArray()
    .Where(p => p.ParagraphFormat.StyleIdentifier == StyleIdentifier.ListBullet);
    
foreach (var bullet in bullets)
{
    listBox19.Items.Add(bullet.GetText().ToString());
}
    
listBox19.Items.Add(bullet1.GetText().ToString());

我也尝试使用 listbullet1,2,3,4 和 5 styleIdentifiers 但这也不能解决问题。

解决方法

很可能您的代码不起作用,因为项目符号不是通过样式应用的。在 MS Word 文档中有几个级别可以应用格式:文档默认值、主题、样式和直接格式。对于您的情况,我认为最好的方法是使用 ListFormat.IsListItem 属性。

,

我现在正在使用它成功地从 word 文件中提取列表项并将它们放入列表框中。

       string fileName = listBox1.Items.Cast<string>().FirstOrDefault();
                // Open the document.
                Document doc = new Document(fileName);

                doc.UpdateListLabels();

                NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph,true);

                // Find if we have the paragraph list. In our document,our list uses plain Arabic numbers,// which start at three and ends at six.
                foreach (Aspose.Words.Paragraph paragraph in paras.OfType<Aspose.Words.Paragraph>().Where(p => p.ListFormat.IsListItem))
                {
                    //listBox19.Items.Add($"List item paragraph #{paras.IndexOf(paragraph)}");

                    // This is the text we get when getting when we output this node to text format.
                    // This text output will omit list labels. Trim any paragraph formatting characters. 
                    string paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
                    //remove the dot in front of the bullet
                    string bullet = paragraphText.Remove(0,2);

                    listBox19.Items.Add(bullet);

                    ListLabel label = paragraph.ListLabel;
                }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...