Biblioteca .NET para crear documentos de procesamiento de texto

Lea, escriba, manipule y convierta archivos de Word, cree tablas en DOCX a través de la API .NET de código abierto.

Open XML SDK es una API de código abierto, desarrollada por Microsoft y distribuida bajo el código de conducta de fuente abierta de Microsoft para manipular documentos de procesamiento de texto, incluidos DOCXDOTXDOCMDOTM

Con la API, puede agregar texto, encabezado, pie de página, notas al final, notas al pie, estilos, temas y más. Le permite generar documentos de Word de alto rendimiento y extraer datos de ellos. La API es compatible con varias plataformas .NET, incluidas .NET 3.5, .NET 4.0, .NET 4.6 y .NET Standard 1.3.

Previous Next

Primeros pasos con Open XML SDK

En primer lugar, debe tener .NET Framework 3.5 o superior. Después de eso, descargue el repositorio manualmente desde GitHub o instálelo desde NuGet.

Instalación Open XML SDK de NuGet

 Install-Package DocumentFormat.OpenXml

Manipular archivo DOCX usando C#

Open XML SDK permite a los programadores de .NET crear y modificar el procesamiento de textos desde sus propias aplicaciones .NET. Para modificar un archivo existente, puede abrir un archivo existente y agregar cambios como texto, párrafos, tablas y más.

Agregar párrafo en DOCX - C#

// Open an existing word processing document
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open("fileformat.docx", true))
{
  Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
  // Add paragraph
  Paragraph para = body.AppendChild(new Paragraph());
  Run run = para.AppendChild(new Run());
  run.AppendChild(new Text("File Format Developer Guide"));
}

Crear una tabla en DOCX usando C#

La API permite a los desarrolladores agregar una tabla en documentos de procesamiento de textos. Puede agregar una tabla, establecer las propiedades de la tabla, establecer la cuadrícula de la tabla y las propiedades de la cuadrícula de la columna. Además, puede administrar celdas y filas de tablas utilizando las clases TableCell y TableRow respectivamente.

Crear tabla en DOCX - C#

// Open an existing word processing document
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open("fileformat.docx", true))
{
  Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
  // Create a table.
  Table table = new Table();
  // Set the style and width for the table.
  TableProperties tableProperties = new TableProperties();
  TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
  // Make the table width 100% of the page width.
  TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };
  // Apply
  tableProperties.Append(tableStyle, tableWidth);
  table.AppendChild(tableProperties);
  // Add columns
  TableGrid tableGrid = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn());
  table.AppendChild(tableGrid);
  // Create 1 row to the table.
  TableRow tableRow = new TableRow();
  // Add a cell to each column in the row.
  TableCell tableCell = new TableCell(new Paragraph(new Run(new Text("Column 1"))));
  TableCell tableCell1 = new TableCell(new Paragraph(new Run(new Text("Column 2"))));
  //Append data
  tableRow.Append(tableCell, tableCell1);
  // Add row to the table.
  table.AppendChild(tableRow);
  // Add the table to the document
  body.AppendChild(table);
}

Encabezados y pies de página en un documento de procesamiento de textos

La organización adecuada de los documentos es muy importante y es la necesidad de toda organización. Los encabezados y pies de página son las partes clave de los documentos que pueden ayudar a organizar correctamente los documentos de procesamiento de texto al colocar información adicional, como fechas relevantes, temas, nombre del autor, imágenes, números de página, etc. También admite la adición de múltiples encabezados.

Administrar encabezados en documentos de Word

 
public static void ApplyHeader(WordprocessingDocument doc)
{
  // Get the main document part.
  MainDocumentPart mainDocPart = doc.MainDocumentPart;
  HeaderPart headerPart1 = mainDocPart.AddNewPart("r97");
  Header header1 = new Header();
  Paragraph paragraph1 = new Paragraph(){ };
  Run run1 = new Run();
  Text text1 = new Text();
  text1.Text = "Header stuff";
  run1.Append(text1);
  paragraph1.Append(run1);
  header1.Append(paragraph1);
  headerPart1.Header = header1;
  SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants().FirstOrDefault();
  if (sectionProperties1 == null)
  {
  sectionProperties1 = new SectionProperties() { };
  mainDocPart.Document.Body.Append(sectionProperties1);
  }
  HeaderReference headerReference1 = new HeaderReference() { Type = HeaderFooterValues.Default, Id = "r97" };
  sectionProperties1.InsertAt(headerReference1,0);
}

Administrar pies de página en un documento de Word

 
public static void ApplyFooter(WordprocessingDocument doc)
{
  // Get the main document part.
  MainDocumentPart mainDocPart = doc.MainDocumentPart;
  FooterPart footerPart1 = mainDocPart.AddNewPart("r98");
  Footer footer1 = new Footer();
  Paragraph paragraph1 = new Paragraph() { };
  Run run1 = new Run();
  Text text1 = new Text();
  text1.Text = "Footer stuff";
  run1.Append(text1);
  paragraph1.Append(run1);
  footer1.Append(paragraph1);
  footerPart1.Footer = footer1;
  SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants().FirstOrDefault();
  if (sectionProperties1 == null)
  {
    sectionProperties1 = new SectionProperties() { };
    mainDocPart.Document.Body.Append(sectionProperties1);
  }
  FooterReference footerReference1 = new FooterReference() { Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98" };
  sectionProperties1.InsertAt(footerReference1, 0);
}
 Español