c# – How to understand the style of text inside a docx file using c #?

Question:

How to understand the style of text in c #? I need to define how the text is written:

  • Italic
  • Bold
  • Underlined
  • Strikethrough
  • Strikethrough

How to actually recognize the face in c # if the text is taken from the word file?

StreamReader readLorem = new StreamReader(@"lorem.docx");

StreamWriter writeEncrypt = new StreamWriter(@"encrypt.docx");

StreamWriter writeDecrypt = new StreamWriter(@"decrypt.docx");

public Bacon()
{
    InitializeComponent();
}

private void Bacon_Load(object sender, EventArgs e)
{
    string lorem = readLorem.ReadToEnd();
}

This code does not preserve the face.

Answer:

As noted earlier, you can use Microsoft's OpenXML library, which you can download here. So, after installation, you need to connect the following assemblies to your project:

  • DocumentFormat.OpenXml
  • WindowsBase

To work with text, you need to include namespaces:

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

For demonstration, I created a small console application for an example, below is a function that parses the formatting of the text that is contained in the file under the path path . This function displays the text from the document and the formatting options for each piece of text:

static void ReadDocx(string path)
{
    try
    {
        using (var doc = WordprocessingDocument.Open(path, false))
        {
            foreach (var p in doc.MainDocumentPart.Document.Body.Elements<Paragraph>())
            {
                foreach (var r in p.Elements<Run>())
                {
                    Console.WriteLine(r.InnerText);
                    Console.WriteLine("Является:");
                    if (r.RunProperties.Bold != null)
                        Console.WriteLine("Жирный");
                    if (r.RunProperties.Italic != null)
                        Console.WriteLine("Курсив");
                    if (r.RunProperties.Underline != null)
                        Console.WriteLine("Подчёркнутый");
                    if (r.RunProperties.Strike != null)
                        Console.WriteLine("Перечеркнутый");
                    if (r.RunProperties.VerticalTextAlignment != null)
                    {
                        if (r.RunProperties.VerticalTextAlignment.Val
                            == VerticalPositionValues.Subscript)
                            Console.WriteLine("Подстрочный");
                        if (r.RunProperties.VerticalTextAlignment.Val
                            == VerticalPositionValues.Superscript)
                            Console.WriteLine("Надстрочный");
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
Scroll to Top