C#/VB.NET: Convert PDF to Linearized
Table of Contents
Installed via NuGet
PM> Install-Package Spire.PDF
Related Links
PDF linearization, also known as "Fast Web View", is a way of optimizing PDF files. Ordinarily, users can view a multipage PDF file online only when their web browsers have downloaded all pages from the server. However, if the PDF file is linearized, the browsers can display the first page very quickly even if the full download has not been completed. This article will demonstrate how to convert a PDF to linearized in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Convert PDF to Linearized
The following are the steps to convert a PDF file to linearized:
- Load a PDF file using PdfToLinearizedPdfConverter class.
- Convert the file to linearized using PdfToLinearizedPdfConverter.ToLinearizedPdf() method.
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Open the result file in Adobe Acrobat and take a look at the document properties, you can see the value of “Fast Web View” is Yes which means the file is linearized.
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Converter PDF em Linearizado
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
A linearização de PDF, também conhecida como "Fast Web View", é uma forma de otimizar arquivos PDF. Normalmente, os usuários podem visualizar um arquivo PDF de várias páginas on-line somente quando seus navegadores tiverem baixado todas as páginas do servidor. Porém, se o arquivo PDF for linearizado, os navegadores poderão exibir a primeira página muito rapidamente, mesmo que o download completo não tenha sido concluído. Este artigo demonstrará como converta um PDF em linearizado em C# e VB.NET usando Spire.PDF for .NET.
Instale o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalados via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Converter PDF em Linearizado
A seguir estão as etapas para converter um arquivo PDF em linearizado:
- Carregue um arquivo PDF usando a classe PdfToLinearizedPdfConverter.
- Converta o arquivo em linearizado usando o método PdfToLinearizedPdfConverter.ToLinearizedPdf().
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Abra o arquivo de resultado no Adobe Acrobat e dê uma olhada nas propriedades do documento, você pode ver que o valor de “Fast Web View” é Sim, o que significa que o arquivo está linearizado.
Solicite uma licença temporária
Se desejar 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: преобразование PDF в линеаризованный
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
Линеаризация PDF, также известная как «Быстрый веб-просмотр», — это способ оптимизации PDF-файлов. Обычно пользователи могут просматривать многостраничный PDF-файл онлайн только тогда, когда их веб-браузеры загрузили все страницы с сервера. Однако если PDF-файл линеаризован, браузеры могут очень быстро отобразить первую страницу, даже если полная загрузка не была завершена. В этой статье будет показано, как конвертировать PDF в линеаризованный в C# и VB.NET используя Spire.PDF for .NET.
Установите Spire.PDF for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.PDF for.NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Конвертировать PDF в линеаризованный
Ниже приведены шаги для преобразования PDF-файла в линеаризованный:
- Загрузите PDF-файл, используя класс PdfToLinearizedPdfConverter.
- Преобразуйте файл в линеаризованный вид с помощью метода PdfToLinearizedPdfConverter.ToLinearizedPdf().
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Откройте файл результатов в Adobe Acrobat и посмотрите на свойства документа. Вы увидите, что значение «Быстрый веб-просмотр» равно «Да», что означает, что файл линеаризован.
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: PDF in linearisiertes konvertieren
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Die PDF-Linearisierung, auch „Fast Web View“ genannt, ist eine Möglichkeit zur Optimierung von PDF-Dateien. Normalerweise können Benutzer eine mehrseitige PDF-Datei nur dann online anzeigen, wenn ihr Webbrowser alle Seiten vom Server heruntergeladen hat. Wenn die PDF-Datei jedoch linearisiert ist, können die Browser die erste Seite sehr schnell anzeigen, auch wenn der vollständige Download noch nicht abgeschlossen ist. Dieser Artikel zeigt, wie das geht Konvertieren Sie ein PDF in ein linearisiertes PDF in C# und VB.NET Verwendung von Spire.PDF for .NET.
Installieren Sie Spire.PDF for .NET
Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
- Package Manager
PM> Install-Package Spire.PDF
Konvertieren Sie PDF in linearisiertes PDF
Im Folgenden sind die Schritte zum Konvertieren einer PDF-Datei in eine linearisierte Datei aufgeführt:
- Laden Sie eine PDF-Datei mit der PdfToLinearizedPdfConverter-Klasse.
- Konvertieren Sie die Datei mit der Methode PdfToLinearizedPdfConverter.ToLinearizedPdf() in eine linearisierte Datei.
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Öffnen Sie die Ergebnisdatei in Adobe Acrobat und werfen Sie einen Blick auf die Dokumenteigenschaften. Sie können sehen, dass der Wert für „Fast Web View“ „Ja“ ist, was bedeutet, dass die Datei linearisiert ist.
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 PDF a Linealizado
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
La linealización de PDF, también conocida como "Vista web rápida", es una forma de optimizar archivos PDF. Normalmente, los usuarios pueden ver un archivo PDF de varias páginas en línea sólo cuando sus navegadores web han descargado todas las páginas del servidor. Sin embargo, si el archivo PDF está linealizado, los navegadores pueden mostrar la primera página muy rápidamente incluso si no se ha completado la descarga completa. Este artículo demostrará cómo convierta un PDF a linealizado en C# y VB.NET usando Spire.PDF for .NET.
Instalar Spire.PDF for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Convertir PDF a Linealizado
Los siguientes son los pasos para convertir un archivo PDF a linealizado:
- Cargue un archivo PDF usando la clase PdfToLinearizedPdfConverter.
- Convierta el archivo a linealizado utilizando el método PdfToLinearizedPdfConverter.ToLinearizedPdf().
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Abra el archivo de resultados en Adobe Acrobat y observe las propiedades del documento; puede ver que el valor de “Fast Web View” es Sí, lo que significa que el archivo está linealizado.
Solicite 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: converti PDF in linearizzato
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
La linearizzazione PDF, nota anche come "Fast Web View", è un modo per ottimizzare i file PDF. Di solito, gli utenti possono visualizzare un file PDF multipagina online solo quando i loro browser web hanno scaricato tutte le pagine dal server. Tuttavia, se il file PDF è linearizzato, i browser possono visualizzare la prima pagina molto rapidamente anche se il download completo non è stato completato. Questo articolo mostrerà come farlo convertire un PDF in linearizzato in C# e VB.NET utilizzando Spire.PDF for .NET.
Installa Spire.PDF for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Converti PDF in linearizzato
Di seguito sono riportati i passaggi per convertire un file PDF in linearizzato:
- Carica un file PDF utilizzando la classe PdfToLinearizedPdfConverter.
- Convertire il file in linearizzato utilizzando il metodo PdfToLinearizedPdfConverter.ToLinearizedPdf().
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Apri il file dei risultati in Adobe Acrobat e dai un'occhiata alle proprietà del documento, puoi vedere che il valore di "Fast Web View" è Sì, il che significa che il file è linearizzato.
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : convertir un PDF en linéarisé
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
La linéarisation PDF, également connue sous le nom de « Fast Web View », est un moyen d'optimiser les fichiers PDF. Habituellement, les utilisateurs ne peuvent visualiser un fichier PDF de plusieurs pages en ligne que lorsque leur navigateur Web a téléchargé toutes les pages du serveur. Cependant, si le fichier PDF est linéarisé, les navigateurs peuvent afficher la première page très rapidement même si le téléchargement complet n'est pas terminé. Cet article montrera comment convertir un PDF en linéarisé en C# et VB.NET en utilisant Spire.PDF for .NET.
Installer Spire.PDF for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Convertir un PDF en linéarisé
Voici les étapes pour convertir un fichier PDF en fichier linéarisé :
- Chargez un fichier PDF à l'aide de la classe PdfToLinearizedPdfConverter.
- Convertissez le fichier en linéarisé à l’aide de la méthode PdfToLinearizedPdfConverter.ToLinearizedPdf().
- C#
- VB.NET
using Spire.Pdf.Conversion; namespace ConvertPdfToLinearized { class Program { static void Main(string[] args) { //Load a PDF file PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("Sample.pdf"); //Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf"); } } }
Imports Spire.Pdf.Conversion Namespace ConvertPdfToLinearized Friend Class Program Private Shared Sub Main(ByVal args As String()) 'Load a PDF file Dim converter As PdfToLinearizedPdfConverter = New PdfToLinearizedPdfConverter("Sample.pdf") 'Convert the file to a linearized PDF converter.ToLinearizedPdf("Linearized.pdf") End Sub End Class End Namespace
Ouvrez le fichier de résultat dans Adobe Acrobat et jetez un œil aux propriétés du document, vous pouvez voir que la valeur de « Fast Web View » est Oui, ce qui signifie que le fichier est linéarisé.
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Create a Table in Word
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
In MS Word, the tables can organize and present data in rows and columns, which makes the information easier to understand and analyze. In this article, you will learn how to programmatically create a table with data in a Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Create a Simple Table in Word
Below are some of the core classes and methods provided by Spire.Doc for .NET for creating and formatting tables in Word.
Name | Description |
Table Class | Represents a table in a Word document. |
TableRow Class | Represents a row in a table. |
TableCell Class | Represents a specific cell in a table. |
Section.AddTbale() Method | Adds a new table to the specified section. |
Table.ResetCells() Method | Resets row number and column number. |
Table.Rows Property | Gets the table rows. |
TableRow.Height Property | Sets the height of the specified row. |
TableRow.Cells Property | Returns the cells collection. |
TableRow.RowFormat Property | Gets the format of the specified row. |
The detailed steps are as follows
- Create a Document object and add a section to it.
- Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
- Add a table to the section using Section.AddTable() method.
- Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
- Insert data to the rest of the rows and apply formatting to these rows.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using System; using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordTable { class Program { static void Main(string[] args) { //Create a Document object Document doc = new Document(); //Add a section Section s = doc.AddSection(); //Define the data for the table String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" }; String[][] data = { new String[]{ "08/07/2021","Dive kayak","United States","24","16"}, new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"}, new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"}, new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"}, new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"}, new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"}, new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"}, new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"}, }; //Add a table Table table = s.AddTable(true); table.ResetCells(data.Length + 1, Header.Length); //Set the first row as table header TableRow FRow = table.Rows[0]; FRow.IsHeader = true; //Set the height and color of the first row FRow.Height = 23; FRow.RowFormat.BackColor = Color.LightSeaGreen; for (int i = 0; i < Header.Length; i++) { //Set alignment for cells Paragraph p = FRow.Cells[i].AddParagraph(); FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TextRange TR = p.AppendText(Header[i]); TR.CharacterFormat.FontName = "Calibri"; TR.CharacterFormat.FontSize = 12; TR.CharacterFormat.Bold = true; } //Add data to the rest of rows and set cell format for (int r = 0; r < data.Length; r++) { TableRow DataRow = table.Rows[r + 1]; DataRow.Height = 20; for (int c = 0; c < data[r].Length; c++) { DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p2 = DataRow.Cells[c].AddParagraph(); TextRange TR2 = p2.AppendText(data[r][c]); p2.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TR2.CharacterFormat.FontName = "Calibri"; TR2.CharacterFormat.FontSize = 11; } } //Save the document doc.SaveToFile("WordTable.docx", FileFormat.Docx2013); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Crie uma tabela no Word
Instalado via NuGet
PM> Install-Package Spire.Doc
Links Relacionados
No MS Word, as tabelas podem organizar e apresentar os dados em linhas e colunas, o que facilita a compreensão e análise das informações. Neste artigo, você aprenderá como programar crie uma tabela com dados em um documento do Word usando Spire.Doc for .NET.
Instale o Spire.Doc for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc 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.Doc
Crie uma tabela simples no Word
Abaixo estão algumas das principais classes e métodos fornecidos pelo Spire.Doc for .NET para criar e formatar tabelas no Word.
Nome | Descrição |
Classe de mesa | Representa uma tabela em um documento do Word. |
Classe TableRow | Representa uma linha em uma tabela. |
Classe TableCell | Representa uma célula específica em uma tabela. |
Método Section.AddTbale() | Adiciona uma nova tabela à seção especificada. |
Método Table.ResetCells() | Redefine o número da linha e o número da coluna. |
Propriedade Table.Rows | Obtém as linhas da tabela. |
Propriedade TableRow.Height | Define a altura da linha especificada. |
Propriedade TableRow.Cells | Retorna a coleção de células. |
Propriedade TableRow.RowFormat | Obtém o formato da linha especificada. |
As etapas detalhadas são as seguintes
- Crie um objeto Document e adicione uma seção a ele.
- Prepare os dados para a linha de cabeçalho e outras linhas, armazenando-os em uma matriz de strings unidimensional e em uma matriz de strings bidimensional, respectivamente.
- Adicione uma tabela à seção usando o método Section.AddTable().
- Insira dados na linha do cabeçalho e defina a formatação da linha, incluindo altura da linha, cor de fundo e alinhamento do texto.
- Insira dados no restante das linhas e aplique formatação a essas linhas.
- Salve o documento em outro arquivo usando o método Document.SaveToFile().
- C#
- VB.NET
using System; using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordTable { class Program { static void Main(string[] args) { //Create a Document object Document doc = new Document(); //Add a section Section s = doc.AddSection(); //Define the data for the table String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" }; String[][] data = { new String[]{ "08/07/2021","Dive kayak","United States","24","16"}, new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"}, new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"}, new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"}, new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"}, new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"}, new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"}, new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"}, }; //Add a table Table table = s.AddTable(true); table.ResetCells(data.Length + 1, Header.Length); //Set the first row as table header TableRow FRow = table.Rows[0]; FRow.IsHeader = true; //Set the height and color of the first row FRow.Height = 23; FRow.RowFormat.BackColor = Color.LightSeaGreen; for (int i = 0; i < Header.Length; i++) { //Set alignment for cells Paragraph p = FRow.Cells[i].AddParagraph(); FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TextRange TR = p.AppendText(Header[i]); TR.CharacterFormat.FontName = "Calibri"; TR.CharacterFormat.FontSize = 12; TR.CharacterFormat.Bold = true; } //Add data to the rest of rows and set cell format for (int r = 0; r < data.Length; r++) { TableRow DataRow = table.Rows[r + 1]; DataRow.Height = 20; for (int c = 0; c < data[r].Length; c++) { DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p2 = DataRow.Cells[c].AddParagraph(); TextRange TR2 = p2.AppendText(data[r][c]); p2.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TR2.CharacterFormat.FontName = "Calibri"; TR2.CharacterFormat.FontSize = 11; } } //Save the document doc.SaveToFile("WordTable.docx", FileFormat.Docx2013); } } }
Solicite uma licença temporária
Se desejar 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
Установлено через NuGet
PM> Install-Package Spire.Doc
Ссылки по теме
В MS Word таблицы могут организовывать и представлять данные в строках и столбцах, что облегчает понимание и анализ информации. В этой статье вы узнаете, как программно создать таблицу с данными в документе Word использование Spire.Doc for .NET.
Установите Spire.Doc for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.Doc
Создать простую таблицу в Word
Ниже приведены некоторые основные классы и методы, предоставляемые Spire.Doc for .NET для создания и форматирования таблиц в Word.
Имя | Описание |
Класс таблицы | Представляет таблицу в документе Word. |
Класс ТаблеРоу | Представляет строку в таблице. |
Класс Таблеселл | Представляет определенную ячейку в таблице. |
Метод Раздел.AddTbale() | Добавляет новую таблицу в указанный раздел. |
Метод Table.ResetCells() | Сбрасывает номер строки и номер столбца. |
Свойство Table.Rows | Получает строки таблицы. |
Свойство TableRow.Height | Устанавливает высоту указанной строки. |
Свойство TableRow.Cells | Возвращает коллекцию ячеек. |
Свойство TableRow.RowFormat | Получает формат указанной строки. |
Подробные шаги следующие:
- Создайте объект Document и добавьте к нему раздел.
- Подготовьте данные для строки заголовка и других строк, сохранив их в одномерном массиве строк и двумерном массиве строк соответственно.
- Добавьте таблицу в раздел с помощью метода Раздел.AddTable().
- Вставьте данные в строку заголовка и задайте форматирование строки, включая высоту строки, цвет фона и выравнивание текста.
- Вставьте данные в остальные строки и примените к этим строкам форматирование.
- Сохраните документ в другой файл, используя метод Document.SaveToFile().
- C#
- VB.NET
using System; using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordTable { class Program { static void Main(string[] args) { //Create a Document object Document doc = new Document(); //Add a section Section s = doc.AddSection(); //Define the data for the table String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" }; String[][] data = { new String[]{ "08/07/2021","Dive kayak","United States","24","16"}, new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"}, new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"}, new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"}, new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"}, new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"}, new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"}, new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"}, }; //Add a table Table table = s.AddTable(true); table.ResetCells(data.Length + 1, Header.Length); //Set the first row as table header TableRow FRow = table.Rows[0]; FRow.IsHeader = true; //Set the height and color of the first row FRow.Height = 23; FRow.RowFormat.BackColor = Color.LightSeaGreen; for (int i = 0; i < Header.Length; i++) { //Set alignment for cells Paragraph p = FRow.Cells[i].AddParagraph(); FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TextRange TR = p.AppendText(Header[i]); TR.CharacterFormat.FontName = "Calibri"; TR.CharacterFormat.FontSize = 12; TR.CharacterFormat.Bold = true; } //Add data to the rest of rows and set cell format for (int r = 0; r < data.Length; r++) { TableRow DataRow = table.Rows[r + 1]; DataRow.Height = 20; for (int c = 0; c < data[r].Length; c++) { DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p2 = DataRow.Cells[c].AddParagraph(); TextRange TR2 = p2.AppendText(data[r][c]); p2.Format.HorizontalAlignment = HorizontalAlignment.Center; //Set data format TR2.CharacterFormat.FontName = "Calibri"; TR2.CharacterFormat.FontSize = 11; } } //Save the document doc.SaveToFile("WordTable.docx", FileFormat.Docx2013); } } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.