C#/VB.NET: Converter Word para Excel
Instalado via NuGet
PM> Install-Package Spire.Office
Links Relacionados
Word e Excel são dois tipos de arquivo completamente diferentes. Os documentos do Word são usados para redigir ensaios, cartas ou criar relatórios, enquanto os documentos do Excel são usados para salvar dados em formato tabular, fazer gráficos ou realizar cálculos matemáticos. Não é recomendado converter um documento complexo do Word em uma planilha do Excel porque o Excel dificilmente pode renderizar o conteúdo de acordo com seu layout original no Word.
No entanto, se o seu documento do Word for composto principalmente de tabelas e você quiser analisar os dados da tabela no Excel, poderá usar o Spire.Office for .NET para converter Word para Excel enquanto mantendo uma boa legibilidade.
Instalar o Spire.Office for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Office for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalado via NuGet.
PM> Install-Package Spire.Office
Converter Word para Excel em C# e VB.NET
Na verdade, esse cenário usa duas bibliotecas no pacote Spire.Office. Eles são Spire.Doc for .NET e Spire.XLS for .NET. O primeiro é usado para ler e extrair conteúdo de um documento do Word, e o segundo é usado para criar um documento do Excel e gravar dados nas células específicas. Para tornar este exemplo de código fácil de entender, criamos os três métodos personalizados a seguir que executam funções específicas.
- ExportTableInExcel() - Exporta dados de uma tabela do Word para células especificadas do Excel.
- CopyContentInTable() - CopyContentInTable() - Copia o conteúdo de uma célula de tabela no Word para uma célula do Excel.
- CopyTextAndStyle() - CopyTextAndStyle() - Copia texto com formatação de um parágrafo do Word para uma célula do Excel.
As etapas a seguir demonstram como exportar dados de um documento inteiro do Word para uma planilha usando o Spire.Office for .NET.
- Crie um objeto Documento para carregar um arquivo do Word.
- Crie um objeto Worbbook e adicione uma planilha chamada "WordToExcel" a ele.
- Percorra todas as seções no documento do Word, percorra todos os objetos de documento em uma determinada seção e determine se um objeto de documento é um parágrafo ou uma tabela.
- Se o objeto do documento for um parágrafo, escreva o parágrafo em uma célula especificada no Excel usando o método CoypTextAndStyle().
- Se o objeto do documento for uma tabela, exporte os dados da tabela de células do Word para Excel usando o método ExportTableInExcel().
- Ajuste automaticamente a altura da linha e a largura da coluna no Excel para que os dados dentro de uma célula não excedam o limite da célula.
- Salve a pasta de trabalho em um arquivo do Excel usando o método Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Solicitar uma licença temporária
Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
C#/VB.NET: преобразование Word в Excel
Оглавление
Установлено через NuGet
PM> Install-Package Spire.Office
Ссылки по теме
Word и Excel — это два совершенно разных типа файлов. Документы Word используются для написания эссе, писем или создания отчетов, а документы Excel используются для сохранения данных в табличной форме, построения диаграмм или выполнения математических расчетов. Не рекомендуется преобразовывать сложный документ Word в электронную таблицу Excel, поскольку Excel едва ли может отображать содержимое в соответствии с его исходным макетом в Word.
Однако если ваш документ Word в основном состоит из таблиц и вы хотите проанализировать табличные данные в Excel, вы можете использовать Spire.Office for .NET для конвертировать ворд в эксель пока сохранение хорошей читабельности.
Установите Spire.Office for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Office for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить с эта ссылка или установлен через NuGet.
PM> Install-Package Spire.Office
Преобразование Word в Excel в C# и VB.NET
Этот сценарий фактически использует две библиотеки в пакете Spire.Office. Это Spire.Doc for .NET и Spire.XLS for .NET. Первый используется для чтения и извлечения содержимого из документа Word, а второй используется для создания документа Excel и записи данных в определенные ячейки. Чтобы упростить понимание этого примера кода, мы создали следующие три пользовательских метода, которые выполняют определенные функции.
- ExportTableInExcel() - Экспорт данных из таблицы Word в указанные ячейки Excel.
- CopyContentInTable() - копирование содержимого из ячейки таблицы Word в ячейку Excel.
- CopyTextAndStyle() - копирование текста с форматированием из абзаца Word в ячейку Excel.
Следующие шаги демонстрируют, как экспортировать данные из всего документа Word на лист с помощью Spire.Office for .NET.
- Создайте объект Document для загрузки файла Word.
- Создайте объект Worbbook и добавьте в него рабочий лист с именем «WordToExcel».
- Просмотрите все разделы в документе Word, просмотрите все объекты документа в определенном разделе, а затем определите, является ли объект документа абзацем или таблицей.
- Если объект документа представляет собой абзац, напишите абзац в указанной ячейке Excel с помощью метода CoypTextAndStyle().
- Если объект документа представляет собой таблицу, экспортируйте данные таблицы из Word в ячейки Excel с помощью метода ExportTableInExcel().
- Автоматически подбирайте высоту строки и ширину столбца в Excel, чтобы данные в ячейке не превышали границу ячейки.
- Сохраните книгу в файл Excel, используя метод Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Word in Excel konvertieren
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Office
verwandte Links
Word und Excel sind zwei völlig unterschiedliche Dateitypen. Word-Dokumente werden zum Schreiben von Aufsätzen, Briefen oder zum Erstellen von Berichten verwendet, während Excel-Dokumente zum Speichern von Daten in tabellarischer Form, zum Erstellen von Diagrammen oder zum Durchführen mathematischer Berechnungen verwendet werden. Es wird nicht empfohlen, ein komplexes Word-Dokument in eine Excel-Tabelle zu konvertieren, da Excel den Inhalt kaum entsprechend seinem ursprünglichen Layout in Word darstellen kann.
Wenn Ihr Word-Dokument jedoch hauptsächlich aus Tabellen besteht und Sie die Tabellendaten in Excel analysieren möchten, können Sie dazu Spire.Office for .NET verwendenKonvertieren Sie Word in Excelwährend Aufrechterhaltung einer guten Lesbarkeit.
Installieren Sie Spire.Office for .NET
Zunächst müssen Sie die im Spire.Office for .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.Office
Konvertieren Sie Word in Excel in C# und VB.NET
In diesem Szenario werden tatsächlich zwei Bibliotheken im Spire.Office-Paket verwendet. Es handelt sich um Spire.Doc for .NET und Spire.XLS for .NET. Ersteres wird zum Lesen und Extrahieren von Inhalten aus einem Word-Dokument verwendet, und letzteres wird zum Erstellen eines Excel-Dokuments und zum Schreiben von Daten in die spezifischen Zellen verwendet. Um dieses Codebeispiel leichter verständlich zu machen, haben wir die folgenden drei benutzerdefinierten Methoden erstellt, die bestimmte Funktionen ausführen.
- ExportTableInExcel() - Daten aus einer Word-Tabelle in bestimmte Excel-Zellen exportieren.
- CopyContentInTable() - Kopieren Sie Inhalte aus einer Tabellenzelle in Word in eine Excel-Zelle.
- CopyTextAndStyle() - Text mit Formatierung aus einem Word-Absatz in eine Excel-Zelle kopieren.
Die folgenden Schritte veranschaulichen, wie Sie mit Spire.Office for .NET Daten aus einem gesamten Word-Dokument in ein Arbeitsblatt exportieren.
- Erstellen Sie ein Document-Objekt, um eine Word-Datei zu laden.
- Erstellen Sie ein Worbbook-Objekt und fügen Sie ihm ein Arbeitsblatt mit dem Namen „WordToExcel“ hinzu.
- Durchlaufen Sie alle Abschnitte im Word-Dokument, durchlaufen Sie alle Dokumentobjekte unter einem bestimmten Abschnitt und bestimmen Sie dann, ob es sich bei einem Dokumentobjekt um einen Absatz oder eine Tabelle handelt.
- Wenn das Dokumentobjekt ein Absatz ist, schreiben Sie den Absatz mithilfe der CoypTextAndStyle()-Methode in eine bestimmte Zelle in Excel.
- Wenn das Dokumentobjekt eine Tabelle ist, exportieren Sie die Tabellendaten mit der Methode ExportTableInExcel() aus Word- in Excel-Zellen.
- Passen Sie die Zeilenhöhe und Spaltenbreite in Excel automatisch an, sodass die Daten in einer Zelle die Zellgrenze nicht überschreiten.
- Speichern Sie die Arbeitsmappe mit der Methode Workbook.SaveToFile() in einer Excel-Datei.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
C#/VB.NET: Convertir Word a Excel
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Office
enlaces relacionados
Word y Excel son dos tipos de archivos completamente diferentes. Los documentos de Word se usan para escribir ensayos, cartas o crear informes, mientras que los documentos de Excel se usan para guardar datos en forma tabular, hacer gráficos o realizar cálculos matemáticos. No se recomienda convertir un documento de Word complejo en una hoja de cálculo de Excel porque difícilmente Excel puede representar el contenido de acuerdo con su diseño original en Word.
Sin embargo, si su documento de Word se compone principalmente de tablas y desea analizar los datos de la tabla en Excel, puede usar Spire.Office for .NET para convertir Word a Excel mientras manteniendo una buena legibilidad.
Instalar Spire.Office for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Office for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalado a través de NuGet.
PM> Install-Package Spire.Office
Convierta Word a Excel en C# y VB.NET
Este escenario en realidad usa dos bibliotecas en el paquete Spire.Office. Son Spire.Doc for .NET y Spire.XLS for .NET. El primero se usa para leer y extraer contenido de un documento de Word, y el segundo se usa para crear un documento de Excel y escribir datos en las celdas específicas. Para que este ejemplo de código sea fácil de entender, creamos los siguientes tres métodos personalizados que realizan funciones específicas.
- ExportTableInExcel() : exporta datos de una tabla de Word a celdas de Excel específicas.
- CopyContentInTable() : copia el contenido de una celda de tabla en Word a una celda de Excel.
- CopyTextAndStyle() : copia texto con formato de un párrafo de Word a una celda de Excel.
Los siguientes pasos demuestran cómo exportar datos de un documento de Word completo a una hoja de trabajo utilizando Spire.Office for .NET.
- Cree un objeto Documento para cargar un archivo de Word.
- Cree un objeto Worbbook y agréguele una hoja de trabajo llamada "WordToExcel".
- Recorra todas las secciones del documento de Word, recorra todos los objetos del documento en una determinada sección y luego determine si un objeto del documento es un párrafo o una tabla.
- Si el objeto del documento es un párrafo, escriba el párrafo en una celda específica en Excel usando el método CoypTextAndStyle().
- Si el objeto del documento es una tabla, exporte los datos de la tabla de celdas de Word a Excel usando el método ExportTableInExcel().
- Ajuste automáticamente el alto de la fila y el ancho de la columna en Excel para que los datos dentro de una celda no excedan el límite de la celda.
- Guarde el libro de trabajo en un archivo de Excel usando el método Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Solicitar una Licencia Temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
C#/VB.NET: Word를 Excel로 변환
NuGet을 통해 설치됨
PM> Install-Package Spire.Office
관련된 링크들
Word와 Excel은 완전히 다른 두 가지 파일 형식입니다. Word 문서는 에세이, 편지를 쓰거나 보고서를 작성하는 데 사용되며 Excel 문서는 데이터를 표 형식으로 저장하거나 차트를 만들거나 수학 계산을 수행하는 데 사용됩니다. Excel은 Word의 원래 레이아웃에 따라 내용을 거의 렌더링할 수 없기 때문에 복잡한 Word 문서를 Excel 스프레드시트로 변환하지 않는 것이 좋습니다.
그러나 Word 문서가 주로 테이블로 구성되어 있고 Excel에서 테이블 데이터를 분석하려는 경우 Spire.Office for .NET 를 사용하여 다음을 수행할 수 있습니다 convert Word to Excel 하면서 좋은 가독성을 유지합니다.
Spire.Office for .NET 설치
먼저 Spire.Office for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 다음에서 다운로드할 수 있습니다 이 링크 또는 NuGet을 통해 설치됩니다.
PM> Install-Package Spire.Office
C# 및 VB.NET에서 Word를 Excel로 변환
이 시나리오는 실제로 Spire.Office 패키지의 두 라이브러리를 사용합니다. Spire.Doc for .NET과 Spire.XLS for .NET입니다. 전자는 Word 문서에서 내용을 읽고 추출하는 데 사용되며 후자는 Excel 문서를 만들고 특정 셀에 데이터를 쓰는 데 사용됩니다. 이 코드 예제를 쉽게 이해할 수 있도록 특정 기능을 수행하는 다음 세 가지 사용자 지정 메서드를 만들었습니다.
- ExportTableInExcel() - Word 테이블의 데이터를 지정된 Excel 셀로 내보냅니다.
- CopyContentInTable() - Word의 표 셀에서 Excel 셀로 내용을 복사합니다.
- CopyTextAndStyle() - Word 단락에서 서식이 있는 텍스트를 Excel 셀로 복사합니다.
다음 단계는 Spire.Office for .NET를 사용하여 전체 Word 문서에서 워크시트로 데이터를 내보내는 방법을 보여줍니다.
- Word 파일을 로드할 문서 개체를 만듭니다.
- Worbbook 개체를 만들고 "WordToExcel"이라는 워크시트를 추가합니다.
- Word 문서의 모든 섹션을 탐색하고 특정 섹션 아래의 모든 문서 개체를 탐색한 다음 문서 개체가 단락인지 표인지 확인합니다.
- 문서 개체가 문단인 경우 CoypTextAndStyle() 메서드를 사용하여 Excel의 지정된 셀에 문단을 작성합니다.
- 문서 개체가 테이블인 경우 ExportTableInExcel() 메서드를 사용하여 Word에서 Excel 셀로 테이블 데이터를 내보냅니다.
- 셀 내의 데이터가 셀 경계를 초과하지 않도록 Excel에서 행 높이와 열 너비를 자동으로 맞춥니다.
- Workbook.SaveToFile() 메서드를 사용하여 통합 문서를 Excel 파일로 저장합니다.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

임시 면허 신청
생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: Converti Word in Excel
Installato tramite NuGet
PM> Install-Package Spire.Office
Link correlati
Word ed Excel sono due tipi di file completamente diversi. I documenti Word vengono utilizzati per scrivere saggi, lettere o creare report, mentre i documenti Excel vengono utilizzati per salvare i dati in forma tabellare, creare grafici o eseguire calcoli matematici. Non è consigliabile convertire un documento Word complesso in un foglio di calcolo Excel perché Excel difficilmente può eseguire il rendering del contenuto in base al layout originale in Word.
Tuttavia, se il documento Word è composto principalmente da tabelle e si desidera analizzare i dati della tabella in Excel, è possibile utilizzare Spire.Office for .NET per convertire Word in Excel Mentre mantenendo una buona leggibilità.
Installa Spire.Office for .NET
Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.Office for .NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.Office
Converti Word in Excel in C# e VB.NET
Questo scenario utilizza effettivamente due librerie nel pacchetto Spire.Office. Sono Spire.Doc for .NET e Spire.XLS for .NET. Il primo viene utilizzato per leggere ed estrarre il contenuto da un documento Word e il secondo viene utilizzato per creare un documento Excel e scrivere dati nelle celle specifiche. Per semplificare la comprensione di questo esempio di codice, abbiamo creato i seguenti tre metodi personalizzati che preformano funzioni specifiche.
- ExportTableInExcel(): esporta i dati da una tabella di Word alle celle di Excel specificate.
- CopyContentInTable() - Copia il contenuto da una cella di tabella in Word a una cella di Excel.
- CopyTextAndStyle() - Copia il testo con la formattazione da un paragrafo di Word a una cella di Excel.
I seguenti passaggi mostrano come esportare i dati da un intero documento di Word in un foglio di lavoro utilizzando Spire.Office for .NET.
- Crea un oggetto Document per caricare un file Word.
- Crea un oggetto Worbbook e aggiungi un foglio di lavoro denominato "WordToExcel".
- Attraversa tutte le sezioni nel documento di Word, attraversa tutti gli oggetti documento in una determinata sezione e quindi determina se un oggetto documento è un paragrafo o una tabella.
- Se l'oggetto documento è un paragrafo, scrivere il paragrafo in una cella specificata in Excel utilizzando il metodo CoypTextAndStyle().
- Se l'oggetto documento è una tabella, esportare i dati della tabella dalle celle di Word alle celle di Excel utilizzando il metodo ExportTableInExcel().
- Adatta automaticamente l'altezza della riga e la larghezza della colonna in Excel in modo che i dati all'interno di una cella non superino il limite della cella.
- Salvare la cartella di lavoro in un file Excel utilizzando il metodo Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : convertir Word en Excel
Table des matières
Installé via NuGet
PM> Install-Package Spire.Office
Liens connexes
Word et Excel sont deux types de fichiers complètement différents. Les documents Word sont utilisés pour rédiger des essais, des lettres ou créer des rapports, tandis que les documents Excel sont utilisés pour enregistrer des données sous forme de tableau, créer des graphiques ou effectuer des calculs mathématiques. Il n'est pas recommandé de convertir un document Word complexe en feuille de calcul Excel car Excel peut difficilement restituer le contenu selon sa mise en page d'origine dans Word.
Toutefois, si votre document Word est principalement composé de tableaux et que vous souhaitez analyser les données du tableau dans Excel, vous pouvez utiliser Spire.Office for .NET pour convertir Word en Excel alors que conservant une bonne lisibilité.
Installer Spire.Office for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Office for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés depuis ce lien ou installé via NuGet.
PM> Install-Package Spire.Office
Convertir Word en Excel en C# et VB.NET
Ce scénario utilise en fait deux bibliothèques dans le package Spire.Office. Ce sont Spire.Doc for .NET et Spire.XLS for .NET. Le premier est utilisé pour lire et extraire le contenu d'un document Word, et le second est utilisé pour créer un document Excel et écrire des données dans les cellules spécifiques. Pour rendre cet exemple de code facile à comprendre, nous avons créé les trois méthodes personnalisées suivantes qui exécutent des fonctions spécifiques.
- ExportTableInExcel() - Exporte les données d'un tableau Word vers des cellules Excel spécifiées.
- CopyContentInTable() - Copie le contenu d'une cellule de tableau dans Word vers une cellule Excel.
- CopyTextAndStyle() - Copie du texte avec mise en forme d'un paragraphe Word vers une cellule Excel.
Les étapes suivantes montrent comment exporter des données d'un document Word entier vers une feuille de calcul à l'aide de Spire.Office for .NET.
- Créez un objet Document pour charger un fichier Word.
- Créez un objet Worbbook et ajoutez-y une feuille de calcul nommée "WordToExcel".
- Parcourez toutes les sections du document Word, parcourez tous les objets de document sous une certaine section, puis déterminez si un objet de document est un paragraphe ou un tableau.
- Si l'objet document est un paragraphe, écrivez le paragraphe dans une cellule spécifiée dans Excel à l'aide de la méthode CoypTextAndStyle().
- Si l'objet document est un tableau, exportez les données du tableau de Word vers des cellules Excel à l'aide de la méthode ExportTableInExcel().
- Ajustez automatiquement la hauteur de ligne et la largeur de colonne dans Excel afin que les données d'une cellule ne dépassent pas la limite de la cellule.
- Enregistrez le classeur dans un fichier Excel à l'aide de la méthode Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: преобразование Word в HTML
Установлено через NuGet
PM> Install-Package Spire.Doc
Ссылки по теме
Если вы хотите разместить документ Word в Интернете, рекомендуется преобразовать документ в HTML, чтобы сделать его доступным через веб-страницу. Эта статья продемонстрирует как конвертировать Word в HTML программно в C# и VB.NET с использованием Spire.Doc for .NET.
Установите Spire.Doc for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить с эта ссылка или установлен через NuGet.
PM> Install-Package Spire.Doc
Преобразование Word в HTML
Следующие шаги показывают, как преобразовать Word в HTML с помощью Spire.Doc for .NET.
- Создайте экземпляр документа.
- Загрузите образец документа Word с помощью метода Document.LoadFromFile().
- Сохраните документ как файл HTML, используя метод Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
namespace WordToHTML
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document mydoc = new Document();
//Load a Word document
mydoc.LoadFromFile("sample.docx");
//Save to HTML
mydoc.SaveToFile("WordToHTML.html", FileFormat.Html);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Converter Excel em PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.XLS
Links Relacionados
Ao converter um arquivo do Excel para o formato PDF, qualquer pessoa pode abrir o arquivo mesmo quando não houver o Office instalado no sistema. Além disso, a conversão de documentos do Excel em PDF é útil, pois os arquivos PDF podem ser facilmente compartilhados e impressos. Neste artigo, você aprenderá como converter um documento inteiro do Excel ou uma planilha específica em PDF usando o Spire.XLS for .NET.
Instalar o Spire.XLS for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.XLS for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.XLS
Converter um documento inteiro do Excel em PDF
A seguir estão as etapas para converter um documento inteiro do Excel em PDF usando o Spire.XLS for .NET.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.LoadFromFile().
- Defina as opções de conversão de Excel para PDF por meio das propriedades na classe ConverterSetting.
- Converta todo o documento do Excel em PDF usando o método Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Converter uma planilha específica para PDF
A seguir estão as etapas para converter uma planilha específica em PDF usando o Spire.XLS for .NET.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.LoadFromFile().
- Defina as opções de conversão de Excel para PDF por meio das propriedades na classe ConverterSetting.
- Obtenha uma planilha específica por meio da propriedade Workbook.Worksheets[index].
- Converta a planilha em PDF usando o método Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Solicitar uma licença temporária
Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
C#/VB.NET: преобразование Excel в PDF
Оглавление
Установлено через NuGet
PM> Install-Package Spire.XLS
Ссылки по теме
Преобразовав файл Excel в формат PDF, любой может открыть файл, даже если в системе не установлен пакет Office. Кроме того, преобразование документов Excel в PDF полезно, поскольку PDF-файлами можно легко делиться и распечатывать. В этой статье вы узнаете, как преобразовать весь документ Excel или конкретный рабочий лист в PDF с помощью Spire.XLS for .NET.
Установите Spire.XLS for .NET
Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.XLS for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить с эта ссылка или установлен через NuGet.
PM> Install-Package Spire.XLS
Преобразование всего документа Excel в PDF
Ниже приведены шаги по преобразованию всего документа Excel в PDF с помощью Spire.XLS for .NET.
- СоздатьРабочая тетрадьобъект.
- Загрузите образец документа Excel с помощью метода Workbook.LoadFromFile().
- Установите параметры преобразования Excel в PDF с помощью свойств в классе ConverterSetting.
- Преобразуйте весь документ Excel в PDF, используя метод Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Преобразование определенного рабочего листа в PDF
Ниже приведены шаги по преобразованию определенного рабочего листа в PDF с помощью Spire.XLS for .NET.
- Создать Рабочая тетрадь объект.
- Загрузите образец документа Excel с помощью метода Workbook.LoadFromFile().
- Установите параметры преобразования Excel в PDF с помощью свойств в классе ConverterSetting.
- Получите конкретный рабочий лист с помощью свойства Workbook.Worksheets[index].
- Преобразуйте рабочий лист в PDF, используя метод Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.