Python: Insert or Extract Images in Word Tables
Images are an effective tool for conveying complex information. By inserting images into tables, you can enhance data presentation with charts, graphs, diagrams, illustrations, and more. This not only enables readers to easily comprehend the information being presented but also adds visual appeal to your document. In certain cases, you may also come across situations where you need to extract images from tables for various purposes. For example, you might want to reuse an image in a presentation, website, or another document. Extracting images allows you to repurpose them, streamlining your content creation process and increasing efficiency. In this article, we will explore how to insert and extract images in Word tables in Python using Spire.Doc for Python.
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Insert Images into a Word Table in Python
Spire.Doc for Python provides the TableCell.Paragraphs[index].AppendPicture() method to add an image to a specific table cell. The detailed steps are as follows.
- Create an object of the Document class.
- Load a Word document using the Document.LoadFromFile() method.
- Get a specific section in the document using the Document.Sections[index] property.
- Get a specific table in the section using the Section.Tables[index] property.
- Access a specific cell in the table using the Table.Row[index].Cells[index] property.
- Add an image to the cell using the TableCell.Paragraphs[index].AppendPicture() method and set the image width and height.
- Save the result document using the Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("Table2.docx")
# Get the first section
section = doc.Sections.get_Item(0)
# Get the first table in the section
table = section.Tables.get_Item(0)
# Add an image to the 3rd cell of the second row in the table
cell = table.Rows[1].Cells[2]
picture = cell.Paragraphs[0].AppendPicture("doc.png")
# Set image width and height
picture.Width = 100
picture.Height = 100
# Add an image to the 3rd cell of the 3rd row in the table
cell = table.Rows[2].Cells[2]
picture = cell.Paragraphs[0].AppendPicture("xls.png")
# Set image width and height
picture.Width = 100
picture.Height = 100
# Save the result document
doc.SaveToFile("AddImagesToTable.docx", FileFormat.Docx2013)
doc.Close()

Extract Images from a Word Table in Python
To extract images from a Word table, you need to iterate through all objects in the table and identify the ones of the DocPicture type. Once the DocPicture objects are found, you can access their image bytes using the DocPicture.ImageBytes property, and then save the image bytes to image files. The detailed steps are as follows.
- Create an object of the Document class.
- Load a Word document using the Document.LoadFromFile() method.
- Get a specific section in the document using the Document.Sections[index] property.
- Get a specific table in the section using the Section.Tables[index] property.
- Create a list to store the extracted image data.
- Iterate through all rows in the table.
- Iterate through all cells in each row.
- Iterate through all paragraphs in each cell.
- Iterate through all child objects in each paragraph.
- Check if the current child object is of DocPicture type.
- Get the image bytes of the DocPicture object using the DocPicture.ImageBytes property and append them to the list.
- Save the image bytes in the list to image files.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("AddImagesToTable.docx")
# Get the first section
section = doc.Sections.get_Item(0)
# Get the first table in the section
table = section.Tables.get_Item(0)
# Create a list to store image bytes
image_data = []
# Iterate through all rows in the table
for i in range(table.Rows.Count):
row = table.Rows.get_Item(i)
# Iterate through all cells in each row
for j in range(row.Cells.Count):
cell = row.Cells[j]
# Iterate through all paragraphs in each cell
for k in range(cell.Paragraphs.Count):
paragraph = cell.Paragraphs[k]
# Iterate through all child objects in each paragraph
for o in range(paragraph.ChildObjects.Count):
child_object = paragraph.ChildObjects[o]
# Check if the current child object is of DocPicture type
if isinstance(child_object, DocPicture):
picture = child_object
# Get the image bytes
bytes = picture.ImageBytes
# Append the image bytes to the list
image_data.append(bytes)
# Save the image bytes in the list to image files
for index, item in enumerate(image_data):
image_Name = f"Images/Image-{index}.png"
with open(image_Name, 'wb') as imageFile:
imageFile.write(item)
doc.Close()

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.
Ler Arquivos Excel em C# Sem Instalar o Excel
Ler um arquivo do Excel em C# é uma tarefa comum para relatórios, importações de dados e automação. Com o Free Spire.XLS for .NET, uma edição comunitária gratuita, você pode carregar uma pasta de trabalho do Excel e ler seus dados sem instalar o Microsoft Excel na máquina e sem usar Interop. Este artigo mostra como ler células, planilhas e linhas, exportar uma planilha para um DataTable e manipular resultados de fórmulas.
Início Rápido: Ler um Arquivo do Excel em C#
Instale o Free Spire.XLS for .NET do NuGet. Execute este comando em um terminal:
dotnet add package FreeSpire.XLS
Ou execute este comando no Console do Gerenciador de Pacotes do NuGet:
Install-Package FreeSpire.XLS
Você também pode baixar o Free Spire.XLS for .NET e referenciar a DLL manualmente, ou encontrar o pacote no NuGet.
O exemplo a seguir carrega um arquivo do Excel, obtém a primeira planilha e imprime o valor da célula A1. Substitua input.xlsx pelo caminho completo do seu arquivo, ou certifique-se de que o arquivo esteja no diretório de trabalho atual do programa.
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
// Load an existing Excel file
workbook.LoadFromFile("input.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Read the value of cell A1 (row 1, column 1)
string value = sheet.Range[1, 1].Value;
Console.WriteLine("Cell A1: " + value);
}
finally
{
workbook.Dispose();
}
}
}
Workbook.LoadFromFile() lê o arquivo na memória. Worksheets[0] retorna a primeira planilha, e Range[1, 1].Value retorna o valor de texto da célula na primeira linha e primeira coluna. O bloco finally libera os recursos da pasta de trabalho quando você termina.

Ler uma Célula ou Planilha Específica
Os exemplos a seguir presumem que workbook já foi carregado com LoadFromFile(). Eles mostram como acessar uma planilha por índice ou nome.
Um arquivo do Excel pode conter várias planilhas. Você pode obter uma planilha por sua posição ou por seu nome:
// By index (zero-based): the first sheet is 0, the second is 1
Worksheet first = workbook.Worksheets[0];
// By name
Worksheet sales = workbook.Worksheets["Sales"];
Você também pode ler uma célula pelos seus números de linha e coluna, ou pelo seu endereço no Excel:
// By row and column numbers (one-based): row 2, column 3
string byIndex = sales.Range[2, 3].Value;
// By Excel address
string byAddress = sales.Range["C2"].Value;
Observe os dois pontos de partida diferentes. A coleção de planilhas é baseada em zero, então a primeira planilha é Worksheets[0]. Os números de linha e coluna das células são baseados em um, então Range[1, 1] é a célula A1.
Para ler um bloco de células, passe um endereço de intervalo e faça um loop por ele:
CellRange range = sales.Range["A1:C3"];
foreach (CellRange cell in range.CellList)
{
Console.WriteLine({BODY_CONTENT}quot;{cell.RangeAddress}: {cell.Value}");
}
Ler Dados do Excel Linha a Linha em C#
Para ler todos os dados de uma planilha, faça um loop pelas linhas com um loop externo e pelas colunas com um loop interno. Escreva uma quebra de linha após cada linha para que a saída do console mantenha a estrutura da planilha:
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];
for (int row = 1; row <= sheet.LastDataRow; row++)
{
for (int col = 1; col <= sheet.LastDataColumn; col++)
{
Console.Write({BODY_CONTENT}quot;{sheet.Range[row, col].Value}\t");
}
Console.WriteLine();
}
}
finally
{
workbook.Dispose();
}
}
}
Os loops vão da linha 1 e coluna 1 até LastDataRow e LastDataColumn, que retornam a última linha e coluna que contêm dados. Isso evita incluir células formatadas, mas vazias, que LastRow e LastColumn abrangeriam. Se sua planilha tiver um layout incomum, verifique o intervalo real no seu arquivo de teste antes de processar a saída.
Para uma planilha que contém os dados de exemplo abaixo:
| Produto | Categoria | Preço |
|---|---|---|
| Teclado | Acessórios | 25 |
| Monitor | Telas | 180 |
o console mostra cada linha da planilha em sua própria linha, com os valores das células separados por tabulações:
Product Category Price
Keyboard Accessories 25
Monitor Displays 180

Ler Dados do Excel em um DataTable
Se você quiser processar dados da planilha com ADO.NET, vinculá-los a um controle ou inseri-los em um banco de dados, exporte a planilha para um DataTable com ExportDataTable():
using System;
using System.Data;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
// Recalculate formulas before exporting computed values
workbook.CalculateAllValue();
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable(
sheet.AllocatedRange,
true, // exportColumnNames
true // computedFormulaValue
);
// Print each row to verify the exported data
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(string.Join("\t", row.ItemArray));
}
}
finally
{
workbook.Dispose();
}
}
}
Esta sobrecarga usa três parâmetros:
- range: o intervalo de células a exportar.
sheet.AllocatedRangeretorna o intervalo usado da planilha. Dependendo da formatação da pasta de trabalho e das configurações de intervalo usado, ele pode incluir células vazias. Se você precisar apenas de uma região de dados específica, use um intervalo explícito e verifique seus limites. - exportColumnNames: quando
true, a primeira linha do intervalo se torna os nomes das colunas doDataTable. Quandofalse, a primeira linha é exportada como dados comuns. - computedFormulaValue: quando
true, o exportador usa valores calculados de fórmulas em vez do texto da fórmula. Quandofalse, as células de fórmula são exportadas como seu texto de fórmula. Se seus dados contiverem fórmulas, verifique os valores exportados no seu próprio arquivo de teste — o cálculo da fórmula pode precisar ser acionado antes da exportação para que os resultados sejam preenchidos corretamente.
Para mostrar o resultado em um aplicativo Windows Forms, atribua a tabela a um DataGridView:
dataGridView1.DataSource = dataTable;
Verifique os nomes das colunas e os tipos de dados da tabela exportada em relação ao seu próprio arquivo do Excel antes de confiar neles em processamentos posteriores. Para mais opções, como exportar um intervalo específico, consulte o tutorial detalhado sobre converter Excel em DataTable em C#.

Ler Resultados de Fórmulas e Manipular Valores de Células
Os trechos nesta seção presumem que sheet se refere a uma planilha de uma pasta de trabalho carregada, como nos exemplos anteriores.
Uma célula que contém uma fórmula tem duas coisas que você pode querer ler: a própria fórmula e o resultado que ela produz. Use HasFormula para verificar se uma célula contém uma fórmula, Formula para obter o texto da fórmula e FormulaValue para obter o resultado calculado. Se você precisar de resultados de fórmulas atualizados, chame workbook.CalculateAllValue() após carregar a pasta de trabalho e antes de ler FormulaValue.
CellRange cell = sheet.Range["D2"];
if (cell.HasFormula)
{
Console.WriteLine("Formula: " + cell.Formula);
Console.WriteLine("Result: " + cell.FormulaValue);
}
else
{
Console.WriteLine("Value: " + cell.Value);
}
Para saber mais sobre como trabalhar com fórmulas, consulte Adicionar ou Ler Fórmulas e Funções no Excel.

Células com diferentes tipos de conteúdo podem ser lidas por meio de propriedades tipadas:
CellRange priceCell = sheet.Range["C2"];
CellRange dateCell = sheet.Range["E2"];
double price = priceCell.NumberValue; // numeric value
DateTime date = dateCell.DateTimeValue; // date value
string text = sheet.Range["A2"].Text; // text as displayed
O Excel armazena números e datas de maneiras diferentes do texto simples, então escolha a propriedade que corresponda ao tipo de dados na célula.
Ler Formatos de Número e Valores Exibidos
Para células com formatos de número — porcentagens, moeda, datas — o valor armazenado, o código de formato e o texto formatado podem ser todos diferentes. Uma célula que armazena 0.15 com um formato de porcentagem é exibida como 15%. Use Value para o valor bruto, NumberFormat para o código de formato e NumberText para o texto como ele aparece no Excel:
| Propriedade | O que ela retorna |
|---|---|
Value |
O valor bruto da célula |
NumberFormat |
O código de formato de número (ex.: 0.00%) |
NumberText |
O texto após aplicar o formato (ex.: 15%) |
CellRange cell = sheet.Range["C2"];
Console.WriteLine("Value: " + cell.Value);
Console.WriteLine("Number format: " + cell.NumberFormat);
Console.WriteLine("Formatted text: " + cell.NumberText);
Escolha a propriedade que corresponde ao que sua lógica subsequente precisa: o valor numérico para cálculos ou o texto formatado para exibição. Para saber mais sobre formatos de número, consulte Definir Formato de Número no Excel.
Antes de ler uma célula, você pode verificar se ela está vazia:
if (string.IsNullOrEmpty(sheet.Range["B5"].Value))
{
Console.WriteLine("B5 is empty.");
}
Perguntas Frequentes
Posso ler arquivos do Excel em C# sem instalar o Microsoft Excel?
Sim. O Free Spire.XLS lê arquivos do Excel diretamente e não requer Microsoft Excel ou Interop no computador ou servidor que executa seu código.
Como faço para ler resultados de fórmulas em vez de fórmulas?
Para uma única célula, verifique CellRange.HasFormula e leia CellRange.FormulaValue. Para ler uma planilha inteira, chame ExportDataTable() com computedFormulaValue definido como true. Consulte Ler Resultados de Fórmulas e Manipular Valores de Células.
Posso ler arquivos do Excel protegidos por senha?
Sim. Defina a senha de abertura antes de carregar o arquivo:
Workbook workbook = new Workbook();
workbook.OpenPassword = "your-password";
workbook.LoadFromFile("protected.xlsx");
Quais formatos de arquivo do Excel o Free Spire.XLS suporta?
O Free Spire.XLS suporta os formatos .xls, .xlsx e .xlsm.
Quais são as limitações da edição gratuita?
O Free Spire.XLS for .NET é uma edição comunitária para desenvolvedores pessoais e pequenos projetos. Ao trabalhar com o formato .xls, cada pasta de trabalho é limitada a 5 planilhas e 200 linhas por planilha. Carregar e salvar arquivos .xlsx não está sujeito a esses limites. Para maior capacidade ou recursos avançados, o Spire.XLS for .NET está disponível como uma edição comercial.
Se você precisar de maior capacidade ou recursos avançados, o Spire.XLS for .NET é a edição comercial — você pode solicitar uma licença de avaliação gratuita de 30 dias para avaliá-lo.
Veja Também
Excel-Dateien in C# lesen ohne Excel zu installieren
Das Lesen einer Excel-Datei in C# ist eine häufige Aufgabe für Berichte, Datenimporte und Automatisierung. Mit Free Spire.XLS for .NET, einer kostenlosen Community-Edition, können Sie eine Excel-Arbeitsmappe laden und ihre Daten lesen, ohne Microsoft Excel auf dem Computer zu installieren und ohne Interop zu verwenden. Dieser Artikel zeigt, wie Sie Zellen, Arbeitsblätter und Zeilen lesen, ein Arbeitsblatt in eine DataTable exportieren und Formelergebnisse behandeln.
Schnellstart: Eine Excel-Datei in C# lesen
Installieren Sie Free Spire.XLS for .NET von NuGet. Führen Sie diesen Befehl in einem Terminal aus:
dotnet add package FreeSpire.XLS
Oder führen Sie diesen Befehl in der NuGet-Paket-Manager-Konsole aus:
Install-Package FreeSpire.XLS
Sie können auch Free Spire.XLS for .NET herunterladen und die DLL manuell referenzieren oder das Paket auf NuGet finden.
Das folgende Beispiel lädt eine Excel-Datei, ruft das erste Arbeitsblatt ab und gibt den Wert der Zelle A1 aus. Ersetzen Sie input.xlsx durch den vollständigen Pfad zu Ihrer Datei, oder stellen Sie sicher, dass sich die Datei im aktuellen Arbeitsverzeichnis des Programms befindet.
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
// Load an existing Excel file
workbook.LoadFromFile("input.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Read the value of cell A1 (row 1, column 1)
string value = sheet.Range[1, 1].Value;
Console.WriteLine("Cell A1: " + value);
}
finally
{
workbook.Dispose();
}
}
}
Workbook.LoadFromFile() liest die Datei in den Arbeitsspeicher. Worksheets[0] gibt das erste Arbeitsblatt zurück, und Range[1, 1].Value gibt den Textwert der Zelle in der ersten Zeile und ersten Spalte zurück. Der finally-Block gibt die Ressourcen der Arbeitsmappe frei, wenn Sie fertig sind.

Eine bestimmte Zelle oder ein Arbeitsblatt lesen
In den folgenden Beispielen wird davon ausgegangen, dass workbook bereits mit LoadFromFile() geladen wurde. Sie zeigen, wie Sie über Index oder Namen auf ein Arbeitsblatt zugreifen.
Eine Excel-Datei kann mehrere Arbeitsblätter enthalten. Sie können ein Arbeitsblatt über seine Position oder seinen Namen abrufen:
// By index (zero-based): the first sheet is 0, the second is 1
Worksheet first = workbook.Worksheets[0];
// By name
Worksheet sales = workbook.Worksheets["Sales"];
Sie können eine Zelle auch über ihre Zeilen- und Spaltennummern oder über ihre Excel-Adresse lesen:
// By row and column numbers (one-based): row 2, column 3
string byIndex = sales.Range[2, 3].Value;
// By Excel address
string byAddress = sales.Range["C2"].Value;
Beachten Sie die beiden unterschiedlichen Startpunkte. Die Arbeitsblattsammlung ist nullbasiert, sodass das erste Arbeitsblatt Worksheets[0] ist. Zellzeilen- und Spaltennummern sind einsbasiert, sodass Range[1, 1] die Zelle A1 ist.
Um einen Zellblock zu lesen, übergeben Sie eine Bereichsadresse und durchlaufen Sie ihn:
CellRange range = sales.Range["A1:C3"];
foreach (CellRange cell in range.CellList)
{
Console.WriteLine({BODY_CONTENT}quot;{cell.RangeAddress}: {cell.Value}");
}
Excel-Daten Zeile für Zeile in C# lesen
Um alle Daten in einem Arbeitsblatt zu lesen, durchlaufen Sie die Zeilen mit einer äußeren Schleife und die Spalten mit einer inneren Schleife. Schreiben Sie nach jeder Zeile einen Zeilenumbruch, damit die Konsolenausgabe die Struktur des Arbeitsblatts beibehält:
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];
for (int row = 1; row <= sheet.LastDataRow; row++)
{
for (int col = 1; col <= sheet.LastDataColumn; col++)
{
Console.Write({BODY_CONTENT}quot;{sheet.Range[row, col].Value}\t");
}
Console.WriteLine();
}
}
finally
{
workbook.Dispose();
}
}
}
Die Schleifen laufen von Zeile 1 und Spalte 1 bis LastDataRow und LastDataColumn, die die letzte Zeile und Spalte zurückgeben, die Daten enthalten. Dadurch werden formatierte, aber leere Zellen vermieden, die LastRow und LastColumn abdecken würden. Wenn Ihr Arbeitsblatt ein ungewöhnliches Layout hat, überprüfen Sie den tatsächlichen Bereich in Ihrer Testdatei, bevor Sie die Ausgabe verarbeiten.
Für ein Arbeitsblatt, das die folgenden Beispieldaten enthält:
| Produkt | Kategorie | Preis |
|---|---|---|
| Tastatur | Zubehör | 25 |
| Monitor | Displays | 180 |
zeigt die Konsole jede Arbeitsblattzeile in einer eigenen Zeile an, wobei die Zellwerte durch Tabs getrennt sind:
Product Category Price
Keyboard Accessories 25
Monitor Displays 180

Excel-Daten in eine DataTable lesen
Wenn Sie Arbeitsblattdaten mit ADO.NET verarbeiten, an ein Steuerelement binden oder in eine Datenbank einfügen möchten, exportieren Sie das Arbeitsblatt mit ExportDataTable() in eine DataTable:
using System;
using System.Data;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
// Recalculate formulas before exporting computed values
workbook.CalculateAllValue();
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable(
sheet.AllocatedRange,
true, // exportColumnNames
true // computedFormulaValue
);
// Print each row to verify the exported data
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(string.Join("\t", row.ItemArray));
}
}
finally
{
workbook.Dispose();
}
}
}
Diese Überladung nimmt drei Parameter an:
- range: der zu exportierende Zellbereich.
sheet.AllocatedRangegibt den verwendeten Bereich des Arbeitsblatts zurück. Abhängig von den Formatierungs- und Einstellungen für den verwendeten Bereich der Arbeitsmappe kann er leere Zellen enthalten. Wenn Sie nur einen bestimmten Datenbereich benötigen, verwenden Sie einen expliziten Bereich und überprüfen Sie dessen Grenzen. - exportColumnNames: Wenn
true, wird die erste Zeile des Bereichs zu den Spaltennamen derDataTable. Wennfalse, wird die erste Zeile als gewöhnliche Daten exportiert. - computedFormulaValue: Wenn
true, verwendet der Exporter berechnete Formelwerte anstelle von Formeltext. Wennfalse, werden Formelzellen als ihr Formeltext exportiert. Wenn Ihre Daten Formeln enthalten, überprüfen Sie die exportierten Werte in Ihrer eigenen Testdatei – die Formelberechnung muss möglicherweise vor dem Export ausgelöst werden, damit die Ergebnisse korrekt gefüllt werden.
Um das Ergebnis in einer Windows Forms-Anwendung anzuzeigen, weisen Sie die Tabelle einem DataGridView zu:
dataGridView1.DataSource = dataTable;
Überprüfen Sie die Spaltennamen und Datentypen der exportierten Tabelle anhand Ihrer eigenen Excel-Datei, bevor Sie sich in der späteren Verarbeitung darauf verlassen. Weitere Optionen, z. B. das Exportieren eines bestimmten Bereichs, finden Sie im ausführlichen Tutorial zum Konvertieren von Excel in DataTable in C#.

Formelergebnisse lesen und Zellwerte behandeln
Die Codeausschnitte in diesem Abschnitt gehen davon aus, dass sheet auf ein Arbeitsblatt aus einer geladenen Arbeitsmappe verweist, wie in den vorherigen Beispielen.
Eine Zelle, die eine Formel enthält, hat zwei Dinge, die Sie möglicherweise lesen möchten: die Formel selbst und das Ergebnis, das sie erzeugt. Verwenden Sie HasFormula, um zu prüfen, ob eine Zelle eine Formel enthält, Formula, um den Formeltext abzurufen, und FormulaValue, um das berechnete Ergebnis abzurufen. Wenn Sie aktuelle Formelergebnisse benötigen, rufen Sie workbook.CalculateAllValue() nach dem Laden der Arbeitsmappe und vor dem Lesen von FormulaValue auf.
CellRange cell = sheet.Range["D2"];
if (cell.HasFormula)
{
Console.WriteLine("Formula: " + cell.Formula);
Console.WriteLine("Result: " + cell.FormulaValue);
}
else
{
Console.WriteLine("Value: " + cell.Value);
}
Weitere Informationen zur Arbeit mit Formeln finden Sie unter Formeln und Funktionen in Excel hinzufügen oder lesen.

Zellen mit unterschiedlichen Inhaltstypen können über typisierte Eigenschaften gelesen werden:
CellRange priceCell = sheet.Range["C2"];
CellRange dateCell = sheet.Range["E2"];
double price = priceCell.NumberValue; // numeric value
DateTime date = dateCell.DateTimeValue; // date value
string text = sheet.Range["A2"].Text; // text as displayed
Excel speichert Zahlen und Datumsangaben anders als reinen Text. Wählen Sie daher die Eigenschaft, die zum Datentyp in der Zelle passt.
Zahlenformate und angezeigte Werte lesen
Bei Zellen mit Zahlenformaten – Prozentsätze, Währung, Datumsangaben – können der gespeicherte Wert, der Formatcode und der formatierte Text alle voneinander abweichen. Eine Zelle, die 0.15 mit einem Prozentformat speichert, wird als 15% angezeigt. Verwenden Sie Value für den Rohwert, NumberFormat für den Formatcode und NumberText für den Text, wie er in Excel erscheint:
| Eigenschaft | Rückgabewert |
|---|---|
Value |
Der Rohwert der Zelle |
NumberFormat |
Der Zahlenformatcode (z. B. 0.00%) |
NumberText |
Der Text nach Anwendung des Formats (z. B. 15%) |
CellRange cell = sheet.Range["C2"];
Console.WriteLine("Value: " + cell.Value);
Console.WriteLine("Number format: " + cell.NumberFormat);
Console.WriteLine("Formatted text: " + cell.NumberText);
Wählen Sie die Eigenschaft, die zu den Anforderungen Ihrer nachgelagerten Logik passt: den numerischen Wert für Berechnungen oder den formatierten Text für die Anzeige. Weitere Informationen zu Zahlenformaten finden Sie unter Zahlenformat in Excel festlegen.
Bevor Sie eine Zelle lesen, können Sie prüfen, ob sie leer ist:
if (string.IsNullOrEmpty(sheet.Range["B5"].Value))
{
Console.WriteLine("B5 is empty.");
}
Häufig gestellte Fragen
Kann ich Excel-Dateien in C# lesen, ohne Microsoft Excel zu installieren?
Ja. Free Spire.XLS liest Excel-Dateien direkt und erfordert weder Microsoft Excel noch Interop auf dem Computer oder Server, auf dem Ihr Code ausgeführt wird.
Wie lese ich Formelergebnisse anstelle von Formeln?
Prüfen Sie für eine einzelne Zelle CellRange.HasFormula und lesen Sie CellRange.FormulaValue. Um ein ganzes Arbeitsblatt zu lesen, rufen Sie ExportDataTable() mit computedFormulaValue auf true auf. Siehe Formelergebnisse lesen und Zellwerte behandeln.
Kann ich passwortgeschützte Excel-Dateien lesen?
Ja. Legen Sie das Öffnungspasswort fest, bevor Sie die Datei laden:
Workbook workbook = new Workbook();
workbook.OpenPassword = "your-password";
workbook.LoadFromFile("protected.xlsx");
Welche Excel-Dateiformate unterstützt Free Spire.XLS?
Free Spire.XLS unterstützt die Formate .xls, .xlsx und .xlsm.
Was sind die Einschränkungen der kostenlosen Edition?
Free Spire.XLS for .NET ist eine Community-Edition für persönliche Entwickler und kleine Projekte. Bei der Arbeit mit dem .xls-Format ist jede Arbeitsmappe auf 5 Arbeitsblätter und 200 Zeilen pro Blatt begrenzt. Das Laden und Speichern von .xlsx-Dateien unterliegt diesen Einschränkungen nicht. Für höhere Kapazität oder erweiterte Funktionen ist Spire.XLS for .NET als kommerzielle Edition erhältlich.
Wenn Sie höhere Kapazität oder erweiterte Funktionen benötigen, ist Spire.XLS for .NET die kommerzielle Edition – Sie können eine kostenlose 30-tägige Testlizenz anfordern, um sie zu evaluieren.
Siehe auch
Leggere file Excel in C# senza installare Excel
Indice
Leggere un file Excel in C# è un'attività comune per report, importazioni di dati e automazione. Con Free Spire.XLS for .NET, un'edizione community gratuita, puoi caricare una cartella di lavoro Excel e leggerne i dati senza installare Microsoft Excel sulla macchina e senza usare Interop. Questo articolo mostra come leggere celle, fogli di lavoro e righe, esportare un foglio di lavoro in una DataTable e gestire i risultati delle formule.
Avvio rapido: leggere un file Excel in C#
Installa Free Spire.XLS for .NET da NuGet. Esegui questo comando in un terminale:
dotnet add package FreeSpire.XLS
Oppure esegui questo comando nella Console di Gestione pacchetti NuGet:
Install-Package FreeSpire.XLS
Puoi anche scaricare Free Spire.XLS for .NET e fare riferimento manualmente alla DLL, oppure trovare il pacchetto su NuGet.
L'esempio seguente carica un file Excel, ottiene il primo foglio di lavoro e stampa il valore della cella A1. Sostituisci input.xlsx con il percorso completo del tuo file, oppure assicurati che il file si trovi nella directory di lavoro corrente del programma.
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
// Load an existing Excel file
workbook.LoadFromFile("input.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Read the value of cell A1 (row 1, column 1)
string value = sheet.Range[1, 1].Value;
Console.WriteLine("Cell A1: " + value);
}
finally
{
workbook.Dispose();
}
}
}
Workbook.LoadFromFile() legge il file in memoria. Worksheets[0] restituisce il primo foglio di lavoro e Range[1, 1].Value restituisce il valore di testo della cella nella prima riga e prima colonna. Il blocco finally rilascia le risorse della cartella di lavoro quando hai finito.

Leggere una cella o un foglio di lavoro specifici
Gli esempi seguenti presuppongono che workbook sia già stato caricato con LoadFromFile(). Mostrano come accedere a un foglio di lavoro tramite indice o nome.
Un file Excel può contenere diversi fogli di lavoro. Puoi ottenere un foglio di lavoro tramite la sua posizione o il suo nome:
// By index (zero-based): the first sheet is 0, the second is 1
Worksheet first = workbook.Worksheets[0];
// By name
Worksheet sales = workbook.Worksheets["Sales"];
Puoi anche leggere una cella tramite i numeri di riga e colonna, oppure tramite il suo indirizzo Excel:
// By row and column numbers (one-based): row 2, column 3
string byIndex = sales.Range[2, 3].Value;
// By Excel address
string byAddress = sales.Range["C2"].Value;
Nota i due diversi punti di partenza. La raccolta di fogli di lavoro è basata su zero, quindi il primo foglio di lavoro è Worksheets[0]. I numeri di riga e colonna delle celle sono basati su uno, quindi Range[1, 1] è la cella A1.
Per leggere un blocco di celle, passa un indirizzo di intervallo e eseguine il loop:
CellRange range = sales.Range["A1:C3"];
foreach (CellRange cell in range.CellList)
{
Console.WriteLine({BODY_CONTENT}quot;{cell.RangeAddress}: {cell.Value}");
}
Leggere i dati di Excel riga per riga in C#
Per leggere tutti i dati in un foglio di lavoro, esegui il loop delle righe con un ciclo esterno e delle colonne con un ciclo interno. Scrivi un'interruzione di riga dopo ogni riga in modo che l'output della console mantenga la struttura del foglio di lavoro:
using System;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];
for (int row = 1; row <= sheet.LastDataRow; row++)
{
for (int col = 1; col <= sheet.LastDataColumn; col++)
{
Console.Write({BODY_CONTENT}quot;{sheet.Range[row, col].Value}\t");
}
Console.WriteLine();
}
}
finally
{
workbook.Dispose();
}
}
}
I cicli vanno dalla riga 1 e colonna 1 fino a LastDataRow e LastDataColumn, che restituiscono l'ultima riga e colonna che contengono dati. Questo evita di includere celle formattate ma vuote che LastRow e LastColumn coprirebbero. Se il tuo foglio di lavoro ha un layout insolito, verifica l'intervallo effettivo sul tuo file di test prima di elaborare l'output.
Per un foglio di lavoro che contiene i dati di esempio seguenti:
| Prodotto | Categoria | Prezzo |
|---|---|---|
| Tastiera | Accessori | 25 |
| Monitor | Display | 180 |
la console mostra ogni riga del foglio di lavoro sulla propria riga, con i valori delle celle separati da tabulazioni:
Product Category Price
Keyboard Accessories 25
Monitor Displays 180

Leggere i dati di Excel in una DataTable
Se vuoi elaborare i dati del foglio di lavoro con ADO.NET, associarli a un controllo o inserirli in un database, esporta il foglio di lavoro in una DataTable con ExportDataTable():
using System;
using System.Data;
using Spire.Xls;
class Program
{
static void Main()
{
Workbook workbook = new Workbook();
try
{
workbook.LoadFromFile("input.xlsx");
// Recalculate formulas before exporting computed values
workbook.CalculateAllValue();
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable(
sheet.AllocatedRange,
true, // exportColumnNames
true // computedFormulaValue
);
// Print each row to verify the exported data
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(string.Join("\t", row.ItemArray));
}
}
finally
{
workbook.Dispose();
}
}
}
Questo overload accetta tre parametri:
- range: l'intervallo di celle da esportare.
sheet.AllocatedRangerestituisce l'intervallo usato del foglio di lavoro. A seconda della formattazione e delle impostazioni dell'intervallo usato della cartella di lavoro, potrebbe includere celle vuote. Se hai bisogno solo di una specifica area di dati, usa un intervallo esplicito e verificane i limiti. - exportColumnNames: quando è
true, la prima riga dell'intervallo diventa i nomi delle colonne dellaDataTable. Quando èfalse, la prima riga viene esportata come dati ordinari. - computedFormulaValue: quando è
true, l'esportatore usa i valori calcolati delle formule invece del testo della formula. Quando èfalse, le celle con formule vengono esportate come testo della formula. Se i tuoi dati contengono formule, verifica i valori esportati sul tuo file di test — il calcolo delle formule potrebbe dover essere attivato prima dell'esportazione affinché i risultati vengano popolati correttamente.
Per mostrare il risultato in un'applicazione Windows Forms, assegna la tabella a una DataGridView:
dataGridView1.DataSource = dataTable;
Controlla i nomi delle colonne e i tipi di dati della tabella esportata rispetto al tuo file Excel prima di fare affidamento su di essi nelle elaborazioni successive. Per ulteriori opzioni, come l'esportazione di un intervallo specifico, consulta il tutorial dettagliato su conversione di Excel in DataTable in C#.

Leggere i risultati delle formule e gestire i valori delle celle
Gli snippet in questa sezione presuppongono che sheet faccia riferimento a un foglio di lavoro di una cartella di lavoro caricata, come negli esempi precedenti.
Una cella che contiene una formula ha due cose che potresti voler leggere: la formula stessa e il risultato che produce. Usa HasFormula per verificare se una cella contiene una formula, Formula per ottenere il testo della formula e FormulaValue per ottenere il risultato calcolato. Se hai bisogno di risultati delle formule aggiornati, chiama workbook.CalculateAllValue() dopo aver caricato la cartella di lavoro e prima di leggere FormulaValue.
CellRange cell = sheet.Range["D2"];
if (cell.HasFormula)
{
Console.WriteLine("Formula: " + cell.Formula);
Console.WriteLine("Result: " + cell.FormulaValue);
}
else
{
Console.WriteLine("Value: " + cell.Value);
}
Per maggiori informazioni sull'uso delle formule, consulta Aggiungere o leggere formule e funzioni in Excel.

Le celle con diversi tipi di contenuto possono essere lette tramite proprietà tipizzate:
CellRange priceCell = sheet.Range["C2"];
CellRange dateCell = sheet.Range["E2"];
double price = priceCell.NumberValue; // numeric value
DateTime date = dateCell.DateTimeValue; // date value
string text = sheet.Range["A2"].Text; // text as displayed
Excel memorizza numeri e date in modi diversi rispetto al testo normale, quindi scegli la proprietà che corrisponde al tipo di dati nella cella.
Leggere i formati numerici e i valori visualizzati
Per le celle con formati numerici — percentuali, valuta, date — il valore memorizzato, il codice di formato e il testo formattato possono tutti differire. Una cella che memorizza 0.15 con un formato percentuale viene visualizzata come 15%. Usa Value per il valore non elaborato, NumberFormat per il codice di formato e NumberText per il testo così come appare in Excel:
| Proprietà | Cosa restituisce |
|---|---|
Value |
Il valore non elaborato della cella |
NumberFormat |
Il codice di formato numerico (ad es. 0.00%) |
NumberText |
Il testo dopo l'applicazione del formato (ad es. 15%) |
CellRange cell = sheet.Range["C2"];
Console.WriteLine("Value: " + cell.Value);
Console.WriteLine("Number format: " + cell.NumberFormat);
Console.WriteLine("Formatted text: " + cell.NumberText);
Scegli la proprietà che corrisponde a ciò di cui ha bisogno la tua logica a valle: il valore numerico per i calcoli o il testo formattato per la visualizzazione. Per maggiori informazioni sui formati numerici, consulta Impostare il formato numerico in Excel.
Prima di leggere una cella, puoi verificare se è vuota:
if (string.IsNullOrEmpty(sheet.Range["B5"].Value))
{
Console.WriteLine("B5 is empty.");
}
Domande frequenti
Posso leggere file Excel in C# senza installare Microsoft Excel?
Sì. Free Spire.XLS legge i file Excel direttamente e non richiede Microsoft Excel o Interop sul computer o server che esegue il tuo codice.
Come posso leggere i risultati delle formule invece delle formule?
Per una singola cella, controlla CellRange.HasFormula e leggi CellRange.FormulaValue. Per leggere un intero foglio di lavoro, chiama ExportDataTable() con computedFormulaValue impostato su true. Vedi Leggere i risultati delle formule e gestire i valori delle celle.
Posso leggere file Excel protetti da password?
Sì. Imposta la password di apertura prima di caricare il file:
Workbook workbook = new Workbook();
workbook.OpenPassword = "your-password";
workbook.LoadFromFile("protected.xlsx");
Quali formati di file Excel supporta Free Spire.XLS?
Free Spire.XLS supporta i formati .xls, .xlsx e .xlsm.
Quali sono i limiti dell'edizione gratuita?
Free Spire.XLS for .NET è un'edizione community per sviluppatori individuali e piccoli progetti. Quando si lavora con il formato .xls, ogni cartella di lavoro è limitata a 5 fogli di lavoro e 200 righe per foglio. Il caricamento e il salvataggio di file .xlsx non sono soggetti a questi limiti. Per capacità superiore o funzionalità avanzate, Spire.XLS for .NET è disponibile come edizione commerciale.
Se hai bisogno di capacità superiore o funzionalità avanzate, Spire.XLS for .NET è l'edizione commerciale — puoi richiedere una licenza di prova gratuita di 30 giorni per valutarla.
Vedi anche
Python: Add or Remove Sections in PowerPoint
In PowerPoint, sections are a powerful tool for organizing and managing slides. By dividing slides into different sections, you can better organize content, navigate through your presentation, and present information in a more structured manner. This article will demonstrate how to add and remove sections in a PowerPoint presentation using Spire.Presentation for Python.
- Add a Section at the End of a PowerPoint
- Insert a Section Before a Specified Section
- Add a Section Before a Specified Slide in PowerPoint
- Remove a Section from a PowerPoint
Install Spire.PDF for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Add a Section at the End of a PowerPoint in Python
Spire.Presentation for Python provides the Presentation.SectionList.Append(section_name) method to add a section at the end of a presentation. Here are the specific steps to perform this operation:
- Create a Presentation class instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Add a section at the end using the Presentation.SectionList.Append() method.
- Save the document using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a new presentation object
presentation = Presentation()
# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")
# Append a new section
presentation.SectionList.Append("New Section")
# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)
# Dispose of the presentation object
presentation.Dispose()

Insert a Section Before a Specified Section in Python
You can also use the Presentation.SectionList.Insert(index, section_name) method to insert a new section before a specific section. Here are the detailed steps:
- Create a Presentation class instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Insert a new section before a specific section using the Presentation.SectionList.Insert() method, where index is the position of the specific section.
- Save the document using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a new presentation object
presentation = Presentation()
# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")
# Insert a new section before the second section
presentation.SectionList.Insert(1," New Section")
# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)
# Dispose of the presentation object
presentation.Dispose()

Add a Section Before a Specified Slide in Python
You can also use the Presentation.SectionList.Add(section_name, slide) method to insert a new section before a specific slide. Here are the detailed steps:
- Create a Presentation class instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Insert a new section before a specific slide using the Presentation.SectionList.Add() method
- Save the document using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a new presentation object
presentation = Presentation()
# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")
# Get the second slide
slide=presentation.Slides[1]
# Add a new section before the second slide
presentation.SectionList.Add("New Section",slide)
# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)
# Dispose of the presentation object
presentation.Dispose()

Remove a Section from a PowerPoint in Python
If you don't need a specific section, you can simply remove it using the Presentation.SectionList.RemoveAt(index_to_remove) method. Please note that removing a section does not delete the slides within that section. Here are the steps to delete a specific section while preserving its slides:
- Create a Presentation class instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Remove a specific section using the Presentation.SectionList.RemoveAt(index_to_remove) method, which takes an integer index as a parameter. You can also remove all sections using the Presentation.Slides.RemoveAll() method.
- Save the document using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a new presentation object
presentation = Presentation()
# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")
# Remove the second section
presentation.SectionList.RemoveAt(1)
# # Remove all sections
# presentation.SectionList.RemoveAll()
# Save the presentation
presentation.SaveToFile("RemoveSection.pptx", FileFormat.Pptx2013)
# Dispose of the presentation object
presentation.Dispose()

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.
Python: Attach Files to a PDF Document
By incorporating supplemental resources directly into the PDF, it consolidates all relevant information in a single file, making it easier to organize, share, and archive. This feature enables users to seamlessly share supporting documents, images, or multimedia elements, eliminating the need for separate file transfers or external links. It streamlines communication, improves efficiency, and ensures that recipients have convenient access to all the necessary resources within the PDF itself. In this article, you will learn how to attach files to a PDF document in Python with the help of Spire.PDF for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Background Knowledge
There are generally two types of attachments in PDF, namely document level attachment and annotation attachment. Both are supported by Spire.PDF for Python. The table below lists the differences between them.
| Attachment type | Represented by | Definition |
| Document level attachment | PdfAttachment class | A file attached to a PDF at the document level won't appear on a page, but can be viewed in the "Attachments" panel of a PDF reader. |
| Annotation attachment | PdfAnnotationAttachment class | A file attached as an annotation can be found on a page or in the "Attachment" panel. An Annotation attachment is shown as a paper clip icon on the page; reviewers can double-click the icon to open the file. |
Attach Files to a PDF Document in Python
To attach files to PDFs at the document level, you first need to create a PdfAttachment object based on an external file, and then you can add it to a PDF document using the PdfDocument.Attachments.Add() method. The following are the detailed steps.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Create a PdfAttachment object based on an external file.
- Add the attachment to the document using PdfDocument.Attachments.Add() method.
- Save the document to a different PDF file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import *
from spire.pdf.common import *
# Create a PdfDocument object
doc = PdfDocument()
# Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")
# Create PdfAttachment objects based on external files
attachment_one = PdfAttachment("C:\\Users\\Administrator\\Desktop\\Data.xlsx")
attachment_two = PdfAttachment("C:\\Users\\Administrator\\Desktop\\logo.png")
# Add the attachments to PDF
doc.Attachments.Add(attachment_one)
doc.Attachments.Add(attachment_two)
# Save to file
doc.SaveToFile("output/Attachment.pdf")

Attach Files as Annotations in PDF in Python
An annotation attachment is represented by the PdfAttachmentAnnotation class. Create an instance of this class, specify its attributes such as bounds, flag and text, and then add it to a specified page using the PdfPageBase.AnnotationsWidget.Add() method.
Below are the steps to attach files as annotations in PDF using Spire.PDF for Python.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get a specific page to add annotation through PdfDocument.Pages[] property.
- Create a PdfAttachmentAnnotation object based on an external file.
- Add the annotation attachment to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the document to a different PDF file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import *
from spire.pdf.common import *
# Create a PdfDocument object
doc = PdfDocument()
# Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")
# Get a specific page
page = doc.Pages.get_Item(1)
# Draw a string on PDF
str = ""Here is the report:""
font = PdfTrueTypeFont(""Times New Roman"", 16.0, PdfFontStyle.Bold, True)
x = 50.0
y = doc.Pages.get_Item(0).ActualSize.Height - 300.0
page.Canvas.DrawString(str, font, PdfBrushes.get_Blue(), x, y)
# Create a PdfAttachmentAnnotation object based on an external file
data = Stream("C:\\Users\\Administrator\\Desktop\\Data.xlsx")
size = font.MeasureString(str);
bounds = RectangleF((x + size.Width + 5.0), y, 10.0, 15.0)
annotation = PdfAttachmentAnnotation(bounds, "Report.docx", data);
# Set color, flag, icon and text of the annotation
annotation.Color = PdfRGBColor(Color.get_Blue())
annotation.Flags = PdfAnnotationFlags.Default
annotation.Icon = PdfAttachmentIcon.Graph
annotation.Text = "Click to open the file"
# Add the attachment annotation to PDF
page.AnnotationsWidget.Add(annotation)
# Save to file
doc.SaveToFile("output/AnnotationAttachment.pdf")

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.
Python: Split a PDF Page into Multiple Pages
Sometimes, when dealing with PDF documents, there is a need to split a page into different sections based on content or layout. For instance, splitting a mixed-layout page with both horizontal and vertical content into two separate parts. This type of splitting is not commonly available in basic PDF management functions but can be important for academic papers, magazine ads, or mixed-layout designs. This article explains how to use Spire.PDF for Python to perform horizontal or vertical PDF page splitting.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Split PDF Page Horizontally or Vertically with Python
Spire.PDF for Python not only supports splitting a PDF document into multiple PDF documents, but also allows splitting a specific page within a PDF into two or more pages. Here are the detailed steps to split a page:
- Create an instance of the PdfDocument class.
- Load the source PDF document using the PdfDocument.LoadFromFile() method.
- Retrieve the page(s) to be split using PdfDocument.Pages[].
- Create a new PDF document and set its page margins to 0.
- Set the width or height of the new document to half of the source document.
- Add a page to the new PDF document using the PdfDocument.Pages.Add() method.
- Create a template for the source document's page using the PdfPageBase.CreateTemplate() method.
- Draw the content of the source page onto the new page using the PdfTemplate.Draw() method.
- Save the split document using the PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
pdf = PdfDocument()
# Load the PDF document
pdf.LoadFromFile("Terms of service.pdf")
# Get the first page
page = doc.Pages.get_Item(0)
# Create a new PDF document and remove the page margins
newpdf = PdfDocument()
newpdf.PageSettings.Margins.All=0
# Horizontal splitting: Set the width of the new document's page to be the same as the width of the first page of the original document, and the height to half of the first page's height
newpdf.PageSettings.Width=page.Size.Width
newpdf.PageSettings.Height=page.Size.Height/2
'''
# Vertical splitting: Set the width of the new document's page to be half of the width of the first page of the original document, and the height to the same as the first page's height
newpdf.PageSettings.Width=page.Size.Width/2
newpdf.PageSettings.Height=page.Size.Height
'''
# Add a new page to the new PDF document
newPage = newpdf.Pages.Add()
# Set the text layout format
format = PdfTextLayout()
format.Break=PdfLayoutBreakType.FitPage
format.Layout=PdfLayoutType.Paginate
# Create a template based on the first page of the original document and draw it onto the new page of the new document, automatically paginating when the page is filled
page.CreateTemplate().Draw(newPage, PointF(0.0, 0.0), format)
# Save the document
newpdf.SaveToFile("HorizontalSplitting.pdf")
# Close the objects
newpdf.Close()
pdf.Close()
The result of horizontal splitting is as follows:

The result of vertical splitting is as follows:

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.
Python: Create a Fillable Form in Word
Creating a fillable form in Word allows you to design a document that can be easily completed and customized by others. Whether you need to collect information, gather feedback, or create an interactive document, fillable forms provide a convenient way to capture data electronically. By adding various elements such as text fields, checkboxes, dropdown menus, and more, you can tailor the form to your specific requirements.
To create a fillable form in Word, you probably need to use the following tools.
- Content Controls: The areas where users input information in a form.
- Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
- Protection: Allows users to populate fields but not to make changes to the rest of the document.
In Word, content controls serve as containers for structured documents, allowing users to organize content within a document. Word 2013 provides ten types of content controls. This article introduces how to create a fillable form in Word that includes the following seven commonly-used content controls using Spire.Doc for Python.
| Content Control | Description |
| Plain Text | A text field limited to plain text, so no formatting can be included. |
| Rich Text | A text field that can contain formatted text or other items, such as tables, pictures, or other content controls. |
| Picture | Accepts a single picture. |
| Drop-Down List | A drop-down list displays a predefined list of items for the user to choose from. |
| Combo Box | A combo box enables users to select a predefined value in a list or type their own value in the text box of the control. |
| Check Box | A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked). |
| Date Picker | Contains a calendar control from which the user can select a date. |
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Create a Fillable Form in Word in Python
Spire.Doc for Python offers the StructureDocumentTagInline class, which is utilized to generate structured document tags within a paragraph. By utilizing the SDTProperties property and SDTContent property of this class, one can define the properties and content of the current structured document tag. Below are the step-by-step instructions for creating a fill form in a Word document in Python.
- Create a Document object.
- Add a section using Document.AddSection() method.
- Add a table using Section.AddTable() method.
- Add a paragraph to a specific table cell using TableCell.AddParagraph() method.
- Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph.ChildObjects.Add() method.
- Specify the type, content and other attributes of the structured document tag through the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object.
- Prevent users from editing content outside form fields using Document.Protect() method.
- Save the document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Add a section
section = doc.AddSection()
# Add a table
table = section.AddTable(True)
table.ResetCells(7, 2)
table.SetColumnWidth(0, 120, CellWidthType.Point)
table.SetColumnWidth(1, 350, CellWidthType.Point)
# Add text to the cells of the first column
paragraph = table.Rows.get_Item(0).Cells.get_Item(0).AddParagraph()
paragraph.AppendText("Name")
paragraph = table.Rows[1].Cells[0].AddParagraph()
paragraph.AppendText("Profile")
paragraph = table.Rows[2].Cells[0].AddParagraph()
paragraph.AppendText("Photo")
paragraph = table.Rows[3].Cells[0].AddParagraph()
paragraph.AppendText("Country")
paragraph = table.Rows[4].Cells[0].AddParagraph()
paragraph.AppendText("Hobbies")
paragraph = table.Rows[5].Cells[0].AddParagraph()
paragraph.AppendText("Birthday")
paragraph = table.Rows[6].Cells[0].AddParagraph()
paragraph.AppendText("Sex")
# Add a plain text content control to the cell (0,1)
paragraph = table.Rows[0].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.Text
sdt.SDTProperties.Alias = "Plain Text"
sdt.SDTProperties.Tag = "Plain Text"
sdt.SDTProperties.IsShowingPlaceHolder = True
text = SdtText(True)
text.IsMultiline = False
sdt.SDTProperties.ControlProperties = text
textRange = TextRange(doc)
textRange.Text = "your name here"
sdt.SDTContent.ChildObjects.Add(textRange)
# Add a rich text content control to the cell (1,1)
paragraph = table.Rows[1].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.RichText
sdt.SDTProperties.Alias = "Rich Text"
sdt.SDTProperties.Tag = "Rich Text"
sdt.SDTProperties.IsShowingPlaceHolder = True
text = SdtText(True)
text.IsMultiline = False
sdt.SDTProperties.ControlProperties = text
textRange = TextRange(doc)
textRange.Text = "brief introduction of yourself"
sdt.SDTContent.ChildObjects.Add(textRange )
# Add a picture content control to the cell (2,1)
paragraph = table.Rows[2].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.Picture
sdt.SDTProperties.Alias = "Picture"
sdt.SDTProperties.Tag = "Picture"
sdtPicture = SdtPicture(True)
sdt.SDTProperties.ControlProperties = sdtPicture
pic = DocPicture(doc)
pic.LoadImage("C:\\Users\\Administrator\\Desktop\\placeHolder.png")
sdt.SDTContent.ChildObjects.Add(pic)
# Add a dropdown list content control to the cell (3,1)
paragraph = table.Rows[3].Cells[1].AddParagraph();
sdt = StructureDocumentTagInline(doc)
sdt.SDTProperties.SDTType = SdtType.DropDownList
sdt.SDTProperties.Alias = "Dropdown List"
sdt.SDTProperties.Tag = "Dropdown List"
paragraph.ChildObjects.Add(sdt)
stdList = SdtDropDownList()
stdList.ListItems.Add(SdtListItem("USA", "1"))
stdList.ListItems.Add(SdtListItem("China", "2"))
stdList.ListItems.Add(SdtListItem("Briza", "3"))
stdList.ListItems.Add(SdtListItem("Austrilia", "4"))
sdt.SDTProperties.ControlProperties = stdList;
textRange = TextRange(doc)
textRange .Text = stdList.ListItems[0].DisplayText
sdt.SDTContent.ChildObjects.Add(textRange )
# Add two check box content controls to the cell (4,1)
paragraph = table.Rows[4].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.CheckBox
sdtCheckBox = SdtCheckBox()
sdt.SDTProperties.ControlProperties = sdtCheckBox
textRange = TextRange(doc)
sdt.ChildObjects.Add(textRange)
sdtCheckBox.Checked = False
paragraph.AppendText(" Movie")
paragraph = table.Rows[4].Cells[1].AddParagraph();
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.CheckBox
sdtCheckBox = SdtCheckBox()
sdt.SDTProperties.ControlProperties = sdtCheckBox
textRange = TextRange(doc)
sdt.ChildObjects.Add(textRange)
sdtCheckBox.Checked = False
paragraph.AppendText(" Game")
# Add a date picker content control to the cell (5,1)
paragraph = table.Rows[5].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.DatePicker
sdt.SDTProperties.Alias = "Date Picker"
sdt.SDTProperties.Tag = "Date Picker"
stdDate = SdtDate()
stdDate.CalendarType = CalendarType.Default
stdDate.DateFormat = "yyyy.MM.dd"
stdDate.FullDate = DateTime.get_Now()
sdt.SDTProperties.ControlProperties = stdDate
textRange = TextRange(doc)
textRange.Text = "your birth date"
sdt.SDTContent.ChildObjects.Add(textRange)
# Add a combo box content control to the cell (6,1)
paragraph = table.Rows[6].Cells[1].AddParagraph()
sdt = StructureDocumentTagInline(doc)
paragraph.ChildObjects.Add(sdt)
sdt.SDTProperties.SDTType = SdtType.ComboBox
sdt.SDTProperties.Alias = "Combo Box"
sdt.SDTProperties.Tag = "Combo Box"
stdComboBox = SdtComboBox()
stdComboBox.ListItems.Add(SdtListItem("Male"))
stdComboBox.ListItems.Add(SdtListItem("Female"))
sdt.SDTProperties.ControlProperties = stdComboBox
textRange = TextRange(doc)
textRange.Text = stdComboBox.ListItems[0].DisplayText
sdt.SDTContent.ChildObjects.Add(textRange)
# Allow users to edit the form fields only
doc.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd")
# Save to file
doc.SaveToFile("output/Form.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.
Python: Add, Edit, or Delete Bookmarks in PDF
PDF bookmarks are navigational aids that allow users to quickly locate and jump to specific sections or pages in a PDF document. Through a simple click, users can arrive at the target location, which eliminates the need to manually scroll or search for specific content in a lengthy document. In this article, you will learn how to programmatically add, modify and delete bookmarks in PDF files using Spire.PDF for Python.
- Add Bookmarks to a PDF Document
- Edit Bookmarks in a PDF Document
- Delete Bookmarks from a PDF Document
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Add Bookmarks to a PDF Document in Python
Spire.PDF for Python provides a method to add bookmarks to a PDF document: PdfDocument. Bookmarks.Add(). You can use this method to create primary bookmarks for the PDF document and use the PdfBookmarkCollection.Add() method to add sub-bookmarks to the primary bookmarks. Additionally, the PdfBookmark class offers other methods to set properties such as destination, text color, and text style for the bookmarks. The following are the detailed steps for adding bookmarks to a PDF document.
- Create a PdfDocument class instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Add a parent bookmark to the document using PdfDocument.Bookmarks.Add() method.
- Create a PdfDestination class object and set the destination of the parent bookmark using PdfBookmark.Action property.
- Set the text color and style of the parent bookmark.
- Create a PdfBookmarkCollection class object to add sub-bookmark to the parent bookmark using PdfBookmarkCollection.Add() method.
- Use the above methods to set the destination, text color, and text style of the sub-bookmark.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Terms of service.pdf")
# Loop through the pages in the PDF file
for i in range(doc.Pages.Count):
page = doc.Pages.get_Item(i)
# Set the title and destination for the bookmark
bookmarkTitle = "Bookmark-{0}".format(i+1)
bookmarkDest = PdfDestination(page, PointF(0.0, 0.0))
# Create and configure the bookmark
bookmark = doc.Bookmarks.Add(bookmarkTitle)
bookmark.Color = PdfRGBColor(Color.get_SaddleBrown())
bookmark.DisplayStyle = PdfTextStyle.Bold
bookmark.Action = PdfGoToAction(bookmarkDest)
# Create a collection to hold child bookmarks
bookmarkColletion = PdfBookmarkCollection(bookmark)
# Set the title and destination for the child bookmark
childBookmarkTitle = "Sub-Bookmark-{0}".format(i+1)
childBookmarkDest = PdfDestination(page, PointF(0.0, 100.0))
# Create and configure the child bookmark
childBookmark = bookmarkColletion.Add(childBookmarkTitle)
childBookmark.Color = PdfRGBColor(Color.get_Coral())
childBookmark.DisplayStyle = PdfTextStyle.Italic
childBookmark.Action = PdfGoToAction(childBookmarkDest)
# Save the PDF file
outputFile = "Bookmark.pdf"
doc.SaveToFile(outputFile)
# Close the document
doc.Close()

Edit Bookmarks in a PDF Document
If you need to update the existing bookmarks, you can use the methods of PdfBookmark class to rename the bookmarks and change their text color, text style. The following are the detailed steps.
- Create a PdfDocument class instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get a specified bookmark using PdfDocument.Bookmarks[] property.
- Change the title of the bookmark using PdfBookmark.Title property.
- Change the font color of the bookmark using PdfBookmark.Color property.
- Change the text style of the bookmark using PdfBookmark.DisplayStyle property.
- Change the text color and style of the sub-bookmark using the above methods.
- Save the result document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Bookmark.pdf")
# Get the first bookmark
bookmark = doc.Bookmarks.get_Item(0)
# Change the title of the bookmark
bookmark.Title = "Modified BookMark"
# Set the color of the bookmark
bookmark.Color = PdfRGBColor(Color.get_Black())
# Set the outline text style of the bookmark
bookmark.DisplayStyle = PdfTextStyle.Bold
# Edit child bookmarks of the parent bookmark
pBookmark = PdfBookmarkCollection(bookmark)
for i in range(pBookmark.Count):
childBookmark = pBookmark.get_Item(i)
childBookmark.Color = PdfRGBColor(Color.get_Blue())
childBookmark.DisplayStyle = PdfTextStyle.Regular
# Save the PDF document
outputFile = "EditBookmark.pdf"
# Close the document
doc.SaveToFile(outputFile)

Delete Bookmarks from a PDF Document
Spire.PDF for Python also provides methods to delete any bookmark in a PDF document. PdfDocument.Bookmarks.RemoveAt() method is used to remove a specific primary bookmark, PdfDocument.Bookmarks.Clear() method is used to remove all bookmarks, and PdfBookmarkCollection.RemoveAt() method is used to remove a specific sub-bookmark of a primary bookmark. The detailed steps of removing bookmarks form a PDF document are as follows.
- Create a PdfDocument class instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the first bookmark using PdfDocument.Bookmarks[] property.
- Remove a specified sub-bookmark of the first bookmark using PdfBookmarkCollection.RemoveAt() method.
- Remove a specified bookmark including its sub-bookmarks using PdfDocument.Bookmarks.RemoveAt() method.
- Remove all bookmarks in the PDF file using PdfDocument.Bookmarks.Clear() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Bookmark.pdf")
# # Delete the first bookmark
# doc.Bookmarks.RemoveAt(0)
# # Get the first bookmark
# bookmark = doc.Bookmarks.get_Item(0)
# # Remove the first child bookmark from first parent bookmark
# pBookmark = PdfBookmarkCollection(bookmark)
# pBookmark.RemoveAt(0)
#Remove all bookmarks
doc.Bookmarks.Clear()
# Save the PDF document
output = "DeleteAllBookmarks.pdf"
doc.SaveToFile(output)
# Close the document
doc.Close()

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.
Python: Convert SVG to PDF
SVG files are commonly used for web graphics and vector-based illustrations because they can be scaled and adjusted easily. PDF, on the other hand, is a versatile format widely supported across different devices and operating systems. Converting SVG to PDF allows for easy sharing of graphics and illustrations, ensuring that recipients can open and view the files without requiring specialized software or worrying about browser compatibility issues. In this article, we will demonstrate how to convert SVG files to PDF format in Python using Spire.PDF for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Convert SVG to PDF in Python
Spire.PDF for Python provides the PdfDocument.LoadFromSvg() method, which allows users to load an SVG file. Once loaded, users can use the PdfDocument.SaveToFile() method to save the SVG file as a PDF file. The detailed steps are as follows.
- Create an object of the PdfDocument class.
- Load an SVG file using PdfDocument.LoadFromSvg() method.
- Save the SVG file to PDF format using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Load an SVG file
doc.LoadFromSvg("Sample.svg")
# Save the SVG file to PDF format
doc.SaveToFile("ConvertSvgToPdf.pdf", FileFormat.PDF)
# Close the PdfDocument object
doc.Close()

Add SVG to PDF in Python
In addition to converting SVG to PDF directly, Spire.PDF for Python also supports adding SVG files to specific locations in PDF. The detailed steps are as follows.
- Create an object of the PdfDocument class.
- Load an SVG file using PdfDocument.LoadFromSvg() method.
- Create a template based on the content of the SVG file using PdfDocument. Pages[].CreateTemplate() method.
- Get the width and height of the template.
- Create another object of the PdfDocument class and load a PDF file using PdfDocument.LoadFromFile() method.
- Draw the template with a custom size at a specific location in the PDF file using PdfDocument.Pages[].Canvas.DrawTemplate() method.
- Save the result file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc1 = PdfDocument()
# Load an SVG file
doc1.LoadFromSvg("Sample.svg")
# Create a template based on the content of the SVG
template = doc1.Pages.get_Item(0).CreateTemplate()
# Get the width and height of the template
width = template.Width
height = template.Height
# Create another PdfDocument object
doc2 = PdfDocument()
# Load a PDF file
doc2.LoadFromFile(""Sample.pdf"")
# Draw the template with a custom size at a specific location on the first page of the loaded PDF file
doc2.Pages.get_Item(0).Canvas.DrawTemplate(template, PointF(10.0, 100.0), SizeF(width*0.8, height*0.8))
# Save the result file
doc2.SaveToFile("AddSvgToPdf.pdf", FileFormat.PDF)
# Close the PdfDocument objects
doc2.Close()
doc1.Close()

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.