Pregunta

Quiero extraer información de las viñetas presentes en un documento de Word.Quiero algo como esto :Supongamos que el texto a continuación está en un documento de Word:

Pasos para arrancar el coche:

  • Puerta abierta
  • siéntate dentro
  • Cierre la puerta
  • Insertar clave
  • etc.

Entonces quiero mi archivo de texto como el siguiente:

Pasos para arrancar el coche:

<BULET>Abrir puerta</BULET>

<BULET> Siéntate adentro </BULET>

<BULET> Cierra la puerta </BULET>

<BULET> Insertar clave </BULET>

<BULET>etc.</BULET>

Estoy usando el lenguaje C# para hacer esto.

Puedo extraer párrafos de un documento de Word y escribirlos directamente en un archivo de texto con cierta información de formato, como si el texto está en negrita o cursiva, etc.pero no sé cómo extraer la información de esta viñeta.

¿Alguien puede decirme cómo hacer esto?

gracias de antemano

¿Fue útil?

Solución 3

Tengo la respuesta .....

En primer lugar yo estaba en la conversión de doc en base párrafo. Pero en lugar de que si procesamos doc frase archivo por base pena, es posible determinar si esa frase contiene bala o cualquier tipo de forma o si esa frase es parte de la mesa. Así que una vez que tengamos esta información, entonces podemos convertir esa frase apropiada. Si alguien necesita código fuente, puedo compartirlo.

Otros consejos

Puede hacerlo mediante la lectura de cada frase. doc.Sentences es una matriz de objeto Range. Para que pueda obtener un mismo objeto de rango Párrafo.

        foreach (Paragraph para in oDoc.Paragraphs)
        {
            string paraNumber = para.Range.ListFormat.ListLevelNumber.ToString();
            string bulletStr = para.Range.ListFormat.ListString;
            MessageBox.Show(paraNumber + "\t" + bulletStr + "\t" + para.Range.Text);
        }

En paraNumber se puede obtener a nivel de párrafo y en buttetStr puede obtener bala como cadena.

Estoy usando esta herramienta OpenXMLPower por Eric White. Su libre y disponible en el paquete Nuget. se puede instalar desde el Administrador de Visual Studio paquete. introducir descripción de la imagen aquí

Se ha proporcionado un producto listo para usar fragmento de código. Esta herramienta me ha salvado muchas horas. A continuación se muestra la forma en que ha personalizado fragmento de código a utilizar para mi requisito. De hecho se puede utilizar estos métodos como en su proyecto.

 private static WordprocessingDocument _wordDocument;
 private StringBuilder textItemSB = new StringBuilder();
 private List<string> textItemList = new List<string>();


/// Open word document using office SDK and reads all contents from body of document
/// </summary>
/// <param name="filepath">path of file to be processed</param>
/// <returns>List of paragraphs with their text contents</returns>
private void GetDocumentBodyContents()
{
    string modifiedString = string.Empty;
    List<string> allList = new List<string>();
    List<string> allListText = new List<string>();

    try
    {
_wordDocument = WordprocessingDocument.Open(wordFileStream, false);
        //RevisionAccepter.AcceptRevisions(_wordDocument);
        XElement root = _wordDocument.MainDocumentPart.GetXDocument().Root;
        XElement body = root.LogicalChildrenContent().First();
        OutputBlockLevelContent(_wordDocument, body);
    }
    catch (Exception ex)
    {
        logger.Error("ERROR in GetDocumentBodyContents:" + ex.Message.ToString());
    }
}


// This is recursive method. At each iteration it tries to fetch listitem and Text item. Once you have these items in hand 
// You can manipulate and create your own collection.
private void OutputBlockLevelContent(WordprocessingDocument wordDoc, XElement blockLevelContentContainer)
{
    try
    {
        string listItem = string.Empty, itemText = string.Empty, numberText = string.Empty;
        foreach (XElement blockLevelContentElement in
            blockLevelContentContainer.LogicalChildrenContent())
        {
            if (blockLevelContentElement.Name == W.p)
            {
                listItem = ListItemRetriever.RetrieveListItem(wordDoc, blockLevelContentElement);
                itemText = blockLevelContentElement
                    .LogicalChildrenContent(W.r)
                    .LogicalChildrenContent(W.t)
                    .Select(t => (string)t)
                    .StringConcatenate();
                if (itemText.Trim().Length > 0)
                {
                    if (null == listItem)
                    {
                        // Add html break tag 
                        textItemSB.Append( itemText + "<br/>");
                    }
                    else
                    {
                        //if listItem == "" bullet character, replace it with equivalent html encoded character                                   
                        textItemSB.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + (listItem == "" ? "&bull;" : listItem) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + itemText + "<br/>");
                    }
                }
                else if (null != listItem)
                {
                    //If bullet character is found, replace it with equivalent html encoded character  
                    textItemSB.Append(listItem == "" ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull;" : listItem);
                }
                else
                    textItemSB.Append("<blank>");
                continue;
            }
            // If element is not a paragraph, it must be a table.

            foreach (var row in blockLevelContentElement.LogicalChildrenContent())
            {                        
                foreach (var cell in row.LogicalChildrenContent())
                {                            
                    // Cells are a block-level content container, so can call this method recursively.
                    OutputBlockLevelContent(wordDoc, cell);
                }
            }
        }
        if (textItemSB.Length > 0)
        {
            textItemList.Add(textItemSB.ToString());
            textItemSB.Clear();
        }
    }
    catch (Exception ex)
    {
        .....
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top