Установить с помощью Pypi

pip install spire.presentation

Похожие ссылки

How to Create a Pie Chart in PowerPoint Presentation

Сделать ваши данные легкими для понимания может быть непросто, особенно если вы не знаете, как превратить цифры в визуальные образы. Если вы когда-либо открывали PowerPoint и задавались вопросом, как быстро создать диаграмму, вы попали по адресу. В этом руководстве вы шаг за шагом узнаете, как создать круговую диаграмму в PowerPoint. Мы рассмотрим все: от добавления диаграммы до настройки цветов и меток, чтобы ваши слайды выглядели четкими и профессиональными. К концу вы сможете представлять свои данные в простой, привлекательной и понятной для всех форме.

Как создать круговую диаграмму в PowerPoint вручную

Создать круговую диаграмму в PowerPoint проще, чем вы думаете. В этой главе мы пошагово проведем вас через этот процесс. Сначала убедитесь, что у вас готовы данные и презентация PowerPoint. Самое главное, на вашем устройстве должен быть установлен Microsoft PowerPoint или другое приложение для редактирования презентаций. В этом руководстве мы будем использовать Microsoft PowerPoint в качестве примера. Как только вы будете готовы, давайте приступим к сегодняшнему руководству.

Шаг 1: Откройте вашу презентацию

Начните с поиска и открытия файла PowerPoint, в который вы хотите добавить диаграмму.

Шаг 2: Выберите слайд

Выберите слайд, на котором должна появиться круговая диаграмма. Убедитесь, что он готов для данных, которые вы хотите показать.

Шаг 3: Вставьте диаграмму

Перейдите на вкладку Вставка на Ленте вверху и нажмите Диаграмма.

Шаг 4: Выберите круговую диаграмму

В диалоговом окне Вставка диаграммы выберите Круговая на левой панели. Вы увидите несколько типов круговых диаграмм �?если вы хотите создать объемную круговую диаграмму на слайде, выберите второй вариант. Нажмите OK, чтобы вставить диаграмму.

Create a Pie Chart in PowerPoint Presentation Manually

Шаг 5: Введите ваши данные

PowerPoint покажет данные по умолчанию в листе, похожем на Excel. Замените их своими собственными цифрами в соответствии с потребностями вашей презентации.

Edit Data

Шаг 6: Настройте диаграмму

Нажмите на диаграмму и перейдите на вкладку Конструктор диаграмм на Ленте. Здесь вы можете изменить стиль, цвета, метки или даже переключиться на другой тип диаграммы. Поэкспериментируйте, пока она не будет выглядеть идеально для вашего слайда.

Вот окончательный вид круговой диаграммы: The Pie Chart Created in Microsoft PowerPoint

Как создать круговую диаграмму в презентации PowerPoint автоматически

После того, как вы научились добавлять круговую диаграмму в PowerPoint вручную, вы, вероятно, заметили, что шаги могут быть немного утомительными, особенно при обновлении данных или настройке диаграммы. Итак, есть ли более быстрый способ?

Использование кода для создания диаграмм �?отличное решение. С помощью Spire.Presentation, профессиональной библиотеки для PowerPoint, вы можете легко создавать диаграммы автоматически, управляя всем: от настройки файла до ввода данных и настройки диаграммы за один раз.

Вот подробное руководство о том, как создать диаграмму в PowerPoint с использованием Spire.Presentation:

Шаг 1: Установите Spire.Presentation

В этом руководстве мы будем использовать Spire.Presentation for Python. Вы можете установить его через pip, открыв свою среду Python (например, терминал VSCode) и выполнив:

pip install spire.presentation

Нажмите Enter, и библиотека будет установлена.

Шаг 2: Напишите код

Вот общая логика создания круговой диаграммы с помощью Spire.Presentation:

  • Импортируйте файл �?Загрузите презентацию PowerPoint, с которой вы хотите работать, или создайте новую.
  • Доступ к целевому слайду �?Выберите слайд, на который будет вставлена круговая диаграмма.
  • Вставьте круговую диаграмму �?Добавьте объект круговой диаграммы на слайд.
  • Установите заголовок диаграммы �?Дайте вашей круговой диаграмме заголовок.
  • Добавьте данные в диаграмму �?Заполните круговую диаграмму вашим набором данных.
  • Настройте цвета диаграммы �?Настройте цвета, чтобы сделать диаграмму визуально привлекательной.

Ниже приведен полный код на Python, показывающий, как создать круговую диаграмму при создании новой презентации PowerPoint:

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation instance
presentation = Presentation()

# Add a pie chart at a specified location on the first slide
rect = RectangleF.FromLTRB (40, 100, 590, 420)
chart = presentation.Slides[0].Shapes.AppendChartInit (ChartType.Pie, rect, False)

# Set and format chart title
chart.ChartTitle.TextProperties.Text = "Sales by Quarter (2024)"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30
chart.HasTitle = True

# Define some data
quarters = ["1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr"]
sales = [210, 320, 180, 460]

# Append data to ChartData, which represents a data table where the chart data is stored
chart.ChartData[0,0].Text = "Quarters"
chart.ChartData[0,1].Text = "Sales"
i = 0
while i < len(quarters):
    chart.ChartData[i + 1,0].Text = quarters[i]
    chart.ChartData[i + 1,1].NumberValue = sales[i]
    i += 1

# Set series labels and category labels
chart.Series.SeriesLabel = chart.ChartData["B1","B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

# Set values for series
chart.Series[0].Values = chart.ChartData["B2","B5"]

# Add data points to series
for i, unusedItem in enumerate(chart.Series[0].Values):
    cdp = ChartDataPoint(chart.Series[0])
    cdp.Index = i
    chart.Series[0].DataPoints.Add(cdp)

# Fill each data point with a different color
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_Honeydew()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_LightPink()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_AliceBlue()

# Set the data labels to display label value and percentage value
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True

# Save the result file
presentation.SaveToFile("E:/Administrator/Python1/output/CreatePieChart.pptx", FileFormat.Pptx2016)
presentation.Dispose()

Вот круговая диаграмма, созданная с помощью Spire.Presentation:

Create a Pie Chart in PowerPoint Presentation with Spire.Presentation

С помощью Spire.Presentation вы можете делать гораздо больше, чем просто создавать круговые диаграммы. Он также позволяет создавать столбчатые диаграммы, линейные диаграммы, гистограммы и многие другие типы визуализаций прямо в ваших слайдах. Кроме того, библиотека поддерживает несколько языков программирования �?предпочитаете ли вы C#, Java, Python или JavaScript, вы можете легко создавать и настраивать диаграммы всего несколькими строками кода.

Заключение

В этом руководстве мы пошагово рассмотрели, как создать круговую диаграмму в PowerPoint, от ручной вставки диаграммы до настройки ее стиля и цветов. Хотя ручной метод хорошо подходит для простых задач, Spire.Presentation работает лучше в сложных ситуациях. С помощью этой профессиональной библиотеки вы можете автоматизировать весь процесс �?от добавления диаграмм и ввода данных до настройки их внешнего вида. Попробуйте его немедленно, получив временную лицензию на 30 дней, что сделает создание диаграмм быстрее и эффективнее, чем когда-либо.

Часто задаваемые вопросы о создании круговой диаграммы в PowerPoint

1. Как мне пошагово создать круговую диаграмму в PowerPoint?

Перейдите в Вставка �?Диаграмма �?Круговая, затем замените образцы данных своими собственными и настройте стиль диаграммы в разделе Конструктор диаграмм.

2. Как я могу показать проценты в круговой диаграмме?

Нажмите на диаграмму, выберите Метки данных �?Дополнительные параметры и установите флажок Проценты, чтобы отображать значения в виде процентов.

3. Как мне сделать круговую диаграмму прогресса в PowerPoint?

Используйте круговую или кольцевую диаграмму с двумя значениями �?прогресс и оставшаяся часть �?и отформатируйте секторы разными цветами.

4. Могу ли я автоматизировать создание круговой диаграммы?

Да. Вы можете использовать Spire.Presentation для автоматического создания и редактирования диаграмм после получения временной лицензии.


ЧИТАЙТЕ ТАКЖЕ

Figura 1 - Da DataFrame Pandas a Excel usando Spire.XLS

Lavorare con dati tabulari è un compito comune per gli sviluppatori Python e Pandas è la libreria di riferimento per la manipolazione e l'analisi dei dati. Spesso, gli sviluppatori devono esportare i DataFrame di Pandas in Excel per la reportistica, la collaborazione in team o ulteriori analisi dei dati. Sebbene Pandas fornisca la funzione to_excel per esportazioni di base, la creazione di report Excel professionali con intestazioni formattate, celle stilizzate, fogli multipli e grafici può essere impegnativa.

Questo tutorial dimostra come scrivere un singolo DataFrame o più DataFrame in Excel utilizzando Spire.XLS per Python, una libreria Excel multifunzionale che consente la personalizzazione completa dei file Excel direttamente da Python, senza la necessità di installare Microsoft Excel.

Indice

Perché usare Spire.XLS per convertire DataFrame Pandas in Excel

Mentre Pandas fornisce funzionalità di esportazione Excel di base, Spire.XLS le estende offrendo il pieno controllo sulla creazione di file Excel. Invece di scrivere semplicemente dati grezzi, gli sviluppatori possono:

  • Organizzare più DataFrame in fogli separati all'interno di un'unica cartella di lavoro.
  • Personalizzare intestazioni, caratteri, colori e formattazione delle celle per produrre layout professionali.
  • Adattare automaticamente le colonne e regolare l'altezza delle righe per una migliore leggibilità.
  • Aggiungere grafici, formule e altre funzionalità di Excel direttamente da Python

Prerequisiti per convertire DataFrame Pandas in Excel

Prima di esportare un DataFrame Pandas in Excel, assicurati di aver installato le seguenti librerie richieste. Puoi farlo eseguendo il seguente comando nel terminale del tuo progetto:

pip install pandas spire.xls

Queste librerie ti consentono di scrivere DataFrame in Excel con fogli multipli, formattazione personalizzata, grafici accattivanti e layout strutturati.

Esportare un singolo DataFrame Pandas in Excel con formattazione

L'esportazione di un singolo DataFrame in un file Excel è lo scenario più comune. Utilizzando Spire.XLS, non solo puoi esportare il tuo DataFrame, ma anche formattare le intestazioni, stilizzare le celle e aggiungere grafici per rendere il tuo report professionale.

Vediamo questo processo passo dopo passo.

Passaggio 1: creare un DataFrame di esempio

Per prima cosa, dobbiamo creare un DataFrame. Qui abbiamo nomi di dipendenti, reparti e stipendi. Ovviamente, puoi sostituirlo con il tuo set di dati.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Passaggio 2: creare una cartella di lavoro e accedere al primo foglio

Ora creeremo una nuova cartella di lavoro Excel e prepareremo il primo foglio di lavoro. Diamo un nome significativo in modo che sia facile da capire.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Passaggio 3: scrivere le intestazioni delle colonne

Scriveremo le intestazioni nella prima riga, le metteremo in grassetto e aggiungeremo uno sfondo grigio chiaro, in modo che tutto appaia ordinato.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Passaggio 4: scrivere le righe di dati

Successivamente, scriviamo ogni riga dal DataFrame. Per i numeri, utilizziamo la proprietà NumberValue in modo che Excel possa riconoscerli per calcoli e grafici.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Passaggio 5: applicare i bordi e adattare automaticamente le colonne

Per dare al tuo foglio Excel un aspetto curato e simile a una tabella, aggiungiamo i bordi e regoliamo automaticamente la larghezza delle colonne.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Passaggio 6: aggiungere un grafico per visualizzare i dati

I grafici ti aiutano a comprendere rapidamente le tendenze. Qui, creeremo un istogramma che confronta gli stipendi.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Passaggio 7: salvare la cartella di lavoro

Infine, salva la cartella di lavoro nella posizione desiderata.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Risultato:

Il file Excel XLSX generato dal DataFrame di Pandas ha questo aspetto:

Figura 2 - Singolo DataFrame Pandas in Excel con formattazione e grafico

Una volta generato il file Excel, può essere ulteriormente elaborato, ad esempio convertito in PDF per una facile condivisione:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Per maggiori dettagli, consulta la guida sulla conversione di Excel in PDF in Python.

Convertire più DataFrame Pandas in un unico file Excel

Quando si creano report in Excel, spesso è necessario inserire più set di dati in fogli separati. Utilizzando Spire.XLS, ogni DataFrame di Pandas può essere scritto nel proprio foglio di lavoro, garantendo che i dati correlati siano organizzati in modo chiaro e facili da analizzare. I seguenti passaggi dimostrano questo flusso di lavoro.

Passaggio 1: creare più DataFrame di esempio

Prima di esportare, creiamo due DataFrame separati: uno per le informazioni sui dipendenti e un altro per i prodotti. Ogni DataFrame andrà nel proprio foglio Excel.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Qui, dataframes è un elenco di tuple che associa ogni DataFrame al nome del foglio in cui dovrebbe apparire.

Passaggio 2: creare una nuova cartella di lavoro

Successivamente, creiamo una nuova cartella di lavoro Excel per memorizzare tutti i DataFrame.

# Create a new workbook
workbook = Workbook()

Questo inizializza una cartella di lavoro vuota con tre fogli predefiniti. Li rinomineremo e popoleremo nel passaggio successivo.

Passaggio 3: scorrere ogni DataFrame e scrivere nel proprio foglio

Invece di scrivere ogni DataFrame individualmente, possiamo scorrere il nostro elenco ed elaborarli allo stesso modo. Ciò riduce il codice duplicato e semplifica la gestione di più set di dati.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

Utilizzando questo ciclo, possiamo facilmente aggiungere più DataFrame in futuro senza riscrivere lo stesso codice.

Passaggio 4: salvare la cartella di lavoro

Infine, salviamo il file Excel. Entrambi i set di dati sono ora ordinatamente organizzati in un unico file con fogli separati, intestazioni formattate e bordi appropriati.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Ora il tuo file Excel è pronto per essere condiviso o analizzato ulteriormente.

Risultato:

Figura 3 - Più DataFrame Pandas in Excel

Il file MultipleDataFrames.xlsx contiene due fogli:

  • Dipendenti (con nomi ed età)
  • Prodotti (con dettagli e prezzi dei prodotti)

Questa organizzazione rende i file Excel multi-report puliti e facili da navigare.

Scrivere DataFrame Pandas in un file Excel esistente

In alcuni casi, invece di creare un nuovo file Excel, potrebbe essere necessario scrivere i DataFrame in una cartella di lavoro esistente. Ciò può essere facilmente ottenuto caricando la cartella di lavoro esistente, aggiungendo un nuovo foglio o accedendo al foglio desiderato e scrivendo i dati del DataFrame utilizzando la stessa logica.

Il codice seguente mostra come scrivere un DataFrame Pandas in un file Excel esistente:

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Figura 4 - Scrivere un DataFrame Pandas in un file Excel esistente

Personalizzazione avanzata per l'esportazione di DataFrame Pandas in Excel

Oltre alle esportazioni di base, i DataFrame di Pandas possono essere personalizzati in Excel per soddisfare requisiti di reporting specifici. Opzioni avanzate, come la selezione di colonne specifiche e l'inclusione o l'esclusione dell'indice, consentono di creare file Excel più puliti, leggibili e professionali. Gli esempi seguenti dimostrano come applicare queste personalizzazioni.

1. Seleziona colonne specifiche

A volte potresti non aver bisogno di esportare tutte le colonne da un DataFrame. Selezionando solo le colonne pertinenti, puoi mantenere i tuoi report Excel concisi e mirati. Il codice seguente dimostra come scorrere le colonne scelte durante la scrittura di intestazioni e righe:

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Includi o escludi indice

Per impostazione predefinita, l'indice del DataFrame non è incluso nell'esportazione. Se il tuo report richiede identificatori di riga o indici numerici, puoi aggiungerli manualmente. Questo frammento di codice mostra come includere l'indice insieme alle colonne selezionate:

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Conclusione

Esportare un DataFrame Pandas in Excel è semplice, ma la produzione di report professionali e ben formattati richiede un controllo aggiuntivo. Utilizzando Pandas per la preparazione dei dati e Spire.XLS per Python per creare e formattare file Excel, è possibile generare cartelle di lavoro strutturate, leggibili e visivamente organizzate. Questo approccio funziona sia per singoli DataFrame che per più set di dati, rendendo facile la creazione di report Excel pronti per l'analisi, la condivisione o ulteriori manipolazioni.

Domande frequenti

D1: Come posso esportare un DataFrame Pandas in Excel in Python?

R1: Puoi usare librerie come Spire.XLS per scrivere un DataFrame in un file Excel. Ciò ti consente di trasferire dati tabulari da Python a Excel mantenendo il controllo sulla formattazione e sul layout.

D2: Posso esportare più di un DataFrame in un singolo file Excel?

R2: Sì. È possibile scrivere più DataFrame in fogli separati all'interno della stessa cartella di lavoro. Ciò aiuta a mantenere i set di dati correlati organizzati in un unico file.

D3: Come aggiungo intestazioni e formatto le celle in Excel da un DataFrame?

R3: Le intestazioni possono essere rese in grassetto, colorate o avere larghezze fisse. I valori numerici possono essere memorizzati come numeri e il testo come stringhe. La formattazione migliora la leggibilità dei report.

D4: È possibile includere grafici nel file Excel esportato?

R4: Sì. Grafici come istogrammi o grafici a linee possono essere aggiunti in base ai dati del tuo DataFrame per aiutare a visualizzare tendenze o confronti.

D5: Ho bisogno di Microsoft Excel installato per esportare i DataFrame?

R5: Non necessariamente. Alcune librerie, tra cui Spire.XLS, possono creare e formattare file Excel interamente in Python senza fare affidamento sull'installazione di Excel.

Vedi anche

Figura 1 - Pandas DataFrame para Excel usando Spire.XLS

Trabalhar com dados tabulares é uma tarefa comum para desenvolvedores Python, e o Pandas é a biblioteca de referência para manipulação e análise de dados. Frequentemente, os desenvolvedores precisam exportar DataFrames do Pandas para o Excel para relatórios, colaboração em equipe ou análise de dados adicional. Embora o Pandas forneça a função to_excel para exportações básicas, criar relatórios profissionais do Excel com cabeçalhos formatados, células estilizadas, várias planilhas e gráficos pode ser um desafio.

Este tutorial demonstra como escrever um único DataFrame ou múltiplos DataFrames para o Excel usando o Spire.XLS for Python, uma biblioteca multifuncional do Excel que permite a personalização completa de arquivos do Excel diretamente do Python, sem a necessidade de ter o Microsoft Excel instalado.

Índice

Por que usar o Spire.XLS para converter DataFrame do Pandas para Excel

Embora o Pandas forneça funcionalidades básicas de exportação para o Excel, o Spire.XLS estende isso, dando controle total sobre a criação de arquivos do Excel. Em vez de apenas escrever dados brutos, os desenvolvedores podem:

  • Organizar múltiplos DataFrames em planilhas separadas dentro de uma única pasta de trabalho.
  • Personalizar cabeçalhos, fontes, cores e formatação de células para produzir layouts profissionais.
  • Ajustar automaticamente as colunas e as alturas das linhas para melhorar a legibilidade.
  • Adicionar gráficos, fórmulas e outros recursos do Excel diretamente do Python

Pré-requisitos para converter DataFrame do Pandas para Excel

Antes de exportar um DataFrame do Pandas para o Excel, certifique-se de ter as seguintes bibliotecas necessárias instaladas. Você pode fazer isso executando o seguinte comando no terminal do seu projeto:

pip install pandas spire.xls

Essas bibliotecas permitem que você escreva DataFrames no Excel com várias planilhas, formatação personalizada, gráficos atraentes e layouts estruturados.

Exportar um único DataFrame do Pandas para Excel com formatação

Exportar um único DataFrame para um arquivo Excel é o cenário mais comum. Usando o Spire.XLS, você pode não apenas exportar seu DataFrame, mas também formatar cabeçalhos, estilizar células e adicionar gráficos para tornar seu relatório com aparência profissional.

Vamos passar por este processo passo a passo.

Passo 1: Criar um DataFrame de Amostra

Primeiro, precisamos criar um DataFrame. Aqui, temos nomes de funcionários, departamentos e salários. Você pode, é claro, substituir isso pelo seu próprio conjunto de dados.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Passo 2: Criar uma Pasta de Trabalho e Acessar a Primeira Planilha

Agora vamos criar uma nova pasta de trabalho do Excel e preparar a primeira planilha. Vamos dar a ela um nome significativo para que seja fácil de entender.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Passo 3: Escrever Cabeçalhos de Coluna

Vamos escrever os cabeçalhos na primeira linha, deixá-los em negrito e adicionar um fundo cinza claro, para que tudo pareça organizado.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Passo 4: Escrever as Linhas de Dados

Em seguida, escrevemos cada linha do DataFrame. Para números, usamos a propriedade NumberValue para que o Excel possa reconhecê-los para cálculos e gráficos.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Passo 5: Aplicar Bordas e Ajustar Colunas Automaticamente

Para dar à sua planilha do Excel uma aparência polida, semelhante a uma tabela, vamos adicionar bordas e ajustar automaticamente a largura das colunas.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Passo 6: Adicionar um Gráfico para Visualizar Dados

Gráficos ajudam você a entender rapidamente as tendências. Aqui, criaremos um gráfico de colunas comparando salários.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Passo 7: Salvar a Pasta de Trabalho

Finalmente, salve a pasta de trabalho no local desejado.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Resultado:

O arquivo Excel XLSX gerado a partir do DataFrame do Pandas se parece com isto:

Figura 2 - Único DataFrame do Pandas para Excel com Formatação e Gráfico

Uma vez que o arquivo Excel é gerado, ele pode ser processado posteriormente, como ser convertido para PDF para fácil compartilhamento:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Para mais detalhes, consulte o guia sobre como converter Excel para PDF em Python.

Converter Múltiplos DataFrames do Pandas para um Único Arquivo Excel

Ao criar relatórios no Excel, vários conjuntos de dados geralmente precisam ser colocados em planilhas separadas. Usando o Spire.XLS, cada DataFrame do Pandas pode ser escrito em sua própria planilha, garantindo que os dados relacionados sejam organizados de forma clara e fáceis de analisar. Os passos a seguir demonstram este fluxo de trabalho.

Passo 1: Criar Múltiplos DataFrames de Amostra

Antes de exportar, criamos dois DataFrames separados - um para informações de funcionários e outro para produtos. Cada DataFrame irá para sua própria planilha do Excel.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Aqui, dataframes é uma lista de tuplas que associa cada DataFrame ao nome da planilha em que deve aparecer.

Passo 2: Criar uma Nova Pasta de Trabalho

Em seguida, criamos uma nova pasta de trabalho do Excel para armazenar todos os DataFrames.

# Create a new workbook
workbook = Workbook()

Isso inicializa uma pasta de trabalho em branco com três planilhas padrão. Vamos renomeá-las e preenchê-las no próximo passo.

Passo 3: Percorrer Cada DataFrame e Escrever em sua Própria Planilha

Em vez de escrever cada DataFrame individualmente, podemos percorrer nossa lista e processá-los da mesma maneira. Isso reduz o código duplicado e facilita o manuseio de mais conjuntos de dados.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

Usando este loop, podemos facilmente adicionar mais DataFrames no futuro sem reescrever o mesmo código.

Passo 4: Salvar a Pasta de Trabalho

Finalmente, salvamos o arquivo Excel. Ambos os conjuntos de dados estão agora organizados de forma limpa em um único arquivo com planilhas separadas, cabeçalhos formatados e bordas adequadas.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Agora seu arquivo Excel está pronto para ser compartilhado ou analisado posteriormente.

Resultado:

Figura 3 - Múltiplos DataFrames do Pandas para Excel

O arquivo MultipleDataFrames.xlsx contém duas planilhas:

  • Funcionários (com nomes e idades)
  • Produtos (com detalhes e preços dos produtos)

Esta organização torna os arquivos Excel com múltiplos relatórios limpos e fáceis de navegar.

Escrever DataFrames do Pandas em um Arquivo Excel Existente

Em alguns casos, em vez de criar um novo arquivo Excel, você pode precisar escrever DataFrames em uma pasta de trabalho existente. Isso pode ser facilmente alcançado carregando a pasta de trabalho existente, adicionando uma nova planilha ou acessando a planilha desejada e escrevendo os dados do DataFrame usando a mesma lógica.

O código a seguir mostra como escrever um DataFrame do Pandas em um arquivo Excel existente:

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Figura 4 - Escrever DataFrame do Pandas em Arquivo Excel Existente

Personalização Avançada para Exportar DataFrames do Pandas para o Excel

Além das exportações básicas, os DataFrames do Pandas podem ser personalizados no Excel para atender a requisitos específicos de relatórios. Opções avançadas - como selecionar colunas específicas e incluir ou excluir o índice - permitem criar arquivos Excel mais limpos, legíveis e profissionais. Os exemplos a seguir demonstram como aplicar essas personalizações.

1. Selecionar Colunas Específicas

Às vezes, você pode não precisar exportar todas as colunas de um DataFrame. Ao selecionar apenas as colunas relevantes, você pode manter seus relatórios do Excel concisos e focados. O código a seguir demonstra como percorrer as colunas escolhidas ao escrever cabeçalhos e linhas:

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Incluir ou Excluir Índice

Por padrão, o índice do DataFrame não é incluído na exportação. Se o seu relatório exigir identificadores de linha ou índices numéricos, você pode adicioná-los manualmente. Este trecho de código mostra como incluir o índice ao lado das colunas selecionadas:

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Conclusão

Exportar um DataFrame do Pandas para o Excel é simples, mas produzir relatórios profissionais e bem formatados requer controle adicional. Usando o Pandas para a preparação de dados e o Spire.XLS for Python para criar e formatar arquivos do Excel, você pode gerar pastas de trabalho estruturadas, legíveis e visualmente organizadas. Essa abordagem funciona tanto para DataFrames únicos quanto para múltiplos conjuntos de dados, facilitando a criação de relatórios do Excel prontos para análise, compartilhamento ou manipulação posterior.

Perguntas Frequentes

P1: Como posso exportar um DataFrame do Pandas para o Excel em Python?

R1: Você pode usar bibliotecas como o Spire.XLS para escrever um DataFrame em um arquivo Excel. Isso permite transferir dados tabulares do Python para o Excel, mantendo o controle sobre a formatação e o layout.

P2: Posso exportar mais de um DataFrame para um único arquivo Excel?

R2: Sim. Múltiplos DataFrames podem ser escritos em planilhas separadas na mesma pasta de trabalho. Isso ajuda a manter conjuntos de dados relacionados organizados em um único arquivo.

P3: Como adiciono cabeçalhos e formato células no Excel a partir de um DataFrame?

R3: Os cabeçalhos podem ser colocados em negrito, coloridos ou ter larguras fixas. Valores numéricos podem ser armazenados como números e texto como strings. A formatação melhora a legibilidade dos relatórios.

P4: É possível incluir gráficos no arquivo Excel exportado?

R4: Sim. Gráficos como os de colunas ou linhas podem ser adicionados com base nos dados do seu DataFrame para ajudar a visualizar tendências ou comparações.

P5: Preciso ter o Microsoft Excel instalado para exportar DataFrames?

R5: Não necessariamente. Algumas bibliotecas, incluindo o Spire.XLS, podem criar e formatar arquivos do Excel inteiramente em Python sem depender da instalação do Excel.

Veja Também

그림 1 - Spire.XLS�?사용하여 Pandas DataFrame�?Excel�?변�?></p>
            <p>테이�?형식 데이�?작업은 Python 개발자에�?일반적인 작업이며 <a href=Pandas�?데이�?조작 �?분석�?위한 기본 라이브러리입니다. 종종 개발자는 보고, 팀 공동 작업 또는 추가 데이�?분석�?위해 Pandas DataFrame�?Excel�?내보내야 합니�? Pandas�?기본 내보내기�?위한 to_excel 함수�?제공하지�?서식�?지정된 헤더, 스타일이 지정된 셀, 여러 시트 �?차트가 포함�?전문적인 Excel 보고서를 만드�?것은 어려�?�?있습니다.

�?자습서에서는 Microsoft Excel�?설치�?필요 없이 Python에서 직접 Excel 파일�?완벽하게 사용�?정의�?�?있는 다기�?Excel 라이브러리인 Spire.XLS for Python�?사용하여 단일 DataFrame 또는 여러 DataFrame�?Excel�?쓰는 방법�?보여줍니�?

목차

Pandas DataFrame�?Excel�?변환하�?�?Spire.XLS�?사용하는 이유

Pandas�?기본 Excel 내보내기 기능�?제공하지�?Spire.XLS�?Excel 파일 생성�?완벽하게 제어하여 이를 확장합니�? 개발자는 원시 데이터를 쓰는 대�?다음�?수행�?�?있습니다.

Pandas DataFrame�?Excel�?변환하�?위한 전제 조건

Pandas DataFrame�?Excel�?내보내기 전에 다음 필수 라이브러리가 설치되어 있는지 확인하십시오. 프로젝트 터미널에�?다음 명령�?실행하여 �?작업�?수행�?�?있습니다.

pip install pandas spire.xls

이러�?라이브러리를 사용하면 여러 시트, 사용�?정의 서식, 매력적인 차트 �?구조화된 레이아웃으로 DataFrame�?Excel�?�?�?있습니다.

서식�?있는 단일 Pandas DataFrame�?Excel�?내보내기

단일 DataFrame�?Excel 파일�?내보내는 것이 가�?일반적인 시나리오입니�? Spire.XLS�?사용하면 DataFrame�?내보�?�?있을 뿐만 아니�?헤더 서식�?지정하�?셀 스타일을 지정하�?차트�?추가하여 보고서를 전문가처럼 보이�?만들 �?있습니다.

�?과정�?단계별로 살펴보겠습니�?

1단계: 샘플 DataFrame 만들�?/h3>

먼저 DataFrame�?만들어야 합니�? 여기에는 직원 이름, 부�?�?급여가 있습니다. 물론 이것�?자신�?데이�?세트�?바꿀 �?있습니다.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

2단계: 통합 문서 만들�?�?�?번째 시트 액세�?/h3>

이제 �?Excel 통합 문서�?만들�?�?번째 워크시트�?준비합니다. 이해하기 쉽도�?의미 있는 이름�?지정해 보겠습니�?

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

3단계: �?헤더 쓰기

헤더�?�?번째 행에 쓰고 굵게 표시하고 밝은 회색 배경�?추가하여 모든 것이 깔끔하게 보이도록 합니�?

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

4단계: 데이�?�?쓰기

다음으로 DataFrame�?�?행을 씁니�? 숫자�?경우 NumberValue 속성�?사용하여 Excel�?계산 �?차트�?대�?인식�?�?있도�?합니�?

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

5단계: 테두�?적용 �?�?자동 맞춤

Excel 시트�?세련�?테이�?모양�?부여하�?위해 테두리를 추가하고 �?너비�?자동으로 조정�?보겠습니�?

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

6단계: 데이�?시각화를 위한 차트 추가

차트�?추세�?빠르�?이해하는 �?도움�?됩니�? 여기서는 급여�?비교하는 세로 막대�?차트�?만들 것입니다.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

7단계: 통합 문서 저�?/h3>

마지막으�?통합 문서�?원하�?위치�?저장합니다.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

결과:

Pandas DataFrame에서 생성�?Excel XLSX 파일은 다음�?같습니다.

그림 2 - 서식 �?차트가 있는 단일 Pandas DataFrame�?Excel�?변�?></p>
            <p>Excel 파일�?생성되면 쉽게 공유�?�?있도�?PDF�?변환하�?�?추가 처리가 가능합니다.</p>
            <pre><code class=workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

자세�?내용은 Python에서 Excel�?PDF�?변�?/a>하는 가이드�?참조하십시오.

여러 Pandas DataFrame�?하나�?Excel 파일�?변�?/h2>

Excel 보고서를 만들 �?여러 데이�?세트�?별도�?시트�?배치해야 하는 경우가 많습니다. Spire.XLS�?사용하면 �?Pandas DataFrame�?자체 워크시트�?�?�?있으므�?관�?데이터가 명확하게 구성되고 분석하기 쉽습니다. 다음 단계�?�?워크플로�?보여줍니�?

1단계: 여러 샘플 DataFrame 만들�?/h3>

내보내기 전에 직원 정보용과 제품용으�?�?개의 개별 DataFrame�?만듭니다. �?DataFrame은 자체 Excel 시트�?들어갑니�?

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

여기�?dataframes�?�?DataFrame�?표시되어�?하는 시트 이름�?쌍으�?연결하는 튜플 목록입니�?

2단계: �?통합 문서 만들�?/h3>

다음으로 모든 DataFrame�?저장할 �?Excel 통합 문서�?만듭니다.

# Create a new workbook
workbook = Workbook()

이렇�?하면 �?개의 기본 시트가 있는 �?통합 문서가 초기화됩니다. 다음 단계에서 이름�?바꾸�?채울 것입니다.

3단계: �?DataFrame�?반복하고 자체 시트�?쓰기

�?DataFrame�?개별적으�?작성하는 대�?목록�?반복하고 동일�?방식으로 처리�?�?있습니다. 이렇�?하면 중복 코드가 줄어들고 �?많은 데이�?세트�?�?쉽게 처리�?�?있습니다.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

�?루프�?사용하면 나중�?동일�?코드�?다시 작성하지 않고�?�?많은 DataFrame�?쉽게 추가�?�?있습니다.

4단계: 통합 문서 저�?/h3>

마지막으�?Excel 파일�?저장합니다. 이제 �?데이�?세트가 모두 별도�?시트, 서식�?지정된 헤더 �?적절�?테두리가 있는 하나�?파일�?깔끔하게 정리되었습니�?

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

이제 Excel 파일�?공유하거�?추가�?분석�?준비가 되었습니�?

결과:

그림 3 - 여러 Pandas DataFrame�?Excel�?변�?></p>
            <p><em>MultipleDataFrames.xlsx</em> 파일에는 �?개의 시트가 있습니다.</p>
            <ul>
                <li>직원 (이름 �?나이 포함)</li>
                <li>제품 (제품 세부 정보 �?가�?포함)</li>
            </ul>
            <p>이러�?구성�?통해 다중 보고�?Excel 파일�?깔끔하고 쉽게 탐색�?�?있습니다.</p>
            <p><a id=

기존 Excel 파일�?Pandas DataFrame 쓰기

경우�?따라 �?Excel 파일�?만드�?대�?기존 통합 문서�?DataFrame�?써야 �?수도 있습니다. 기존 통합 문서�?로드하고 �?시트�?추가하거�?원하�?시트�?액세스한 다음 동일�?논리�?사용하여 DataFrame 데이터를 작성하면 �?작업�?쉽게 수행�?�?있습니다.

다음 코드�?Pandas DataFrame�?기존 Excel 파일�?쓰는 방법�?보여줍니�?

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

그림 4 - 기존 Excel 파일�?Pandas DataFrame 쓰기

Pandas DataFrame�?Excel�?내보내기 위한 고급 사용�?정의

기본 내보내기 외에�?특정 보고 요구 사항�?충족하도�?Excel에서 Pandas DataFrame�?사용�?정의�?�?있습니다. 특정 �?선택, 인덱�?포함 또는 제외와 같은 고급 옵션�?사용하면 �?깨끗하고 읽기 쉬우�?전문적인 Excel 파일�?만들 �?있습니다. 다음 예에서는 이러�?사용�?정의�?적용하는 방법�?보여줍니�?

1. 특정 �?선택

경우�?따라 DataFrame�?모든 열을 내보�?필요가 없을 수도 있습니다. 관�?열만 선택하여 Excel 보고서를 간결하고 집중적으�?유지�?�?있습니다. 다음 코드�?헤더와 행을 작성�?�?선택�?열을 반복하는 방법�?보여줍니�?

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. 인덱�?포함 또는 제외

기본적으�?DataFrame 인덱스는 내보내기�?포함되지 않습니다. 보고서에 �?식별자나 숫자 인덱스가 필요�?경우 수동으로 추가�?�?있습니다. �?코드 조각은 선택�?열과 함께 인덱스를 포함하는 방법�?보여줍니�?

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

결론

Pandas DataFrame�?Excel�?내보내는 것은 간단하지�?전문적이�?�?서식�?보고서를 작성하려�?추가 제어가 필요합니�? 데이�?준비를 위해 Pandas�?사용하고 Excel 파일�?만들�?서식�?지정하�?위해 Spire.XLS for Python�?사용하면 구조화되�?읽기 쉬우�?시각적으�?구성�?통합 문서�?생성�?�?있습니다. �?접근 방식은 단일 DataFrame�?여러 데이�?세트 모두�?적용되므�?분석, 공유 또는 추가 조작�?위해 준비된 Excel 보고서를 쉽게 만들 �?있습니다.

자주 묻는 질문

Q1: Python에서 Pandas DataFrame�?Excel�?어떻�?내보�?�?있나�?

A1: Spire.XLS와 같은 라이브러리를 사용하여 DataFrame�?Excel 파일�?�?�?있습니다. 이를 통해 서식 �?레이아웃�?대�?제어�?유지하면�?테이�?형식 데이터를 Python에서 Excel�?전송�?�?있습니다.

Q2: �?이상�?DataFrame�?단일 Excel 파일�?내보�?�?있나�?

A2: �? 여러 DataFrame�?동일�?통합 문서 내의 별도 시트�?�?�?있습니다. 이렇�?하면 관�?데이�?세트�?하나�?파일�?정리하는 �?도움�?됩니�?

Q3: DataFrame에서 Excel�?헤더�?추가하고 셀 서식�?어떻�?지정하나요?

A3: 헤더�?굵게 표시하거�?색상�?지정하거나 고정 너비�?가�?�?있습니다. 숫자 값은 숫자�? 텍스트는 문자열로 저장할 �?있습니다. 서식�?지정하�?보고서의 가독성�?향상됩니�?

Q4: 내보�?Excel 파일�?차트�?포함�?�?있나�?

A4: �? DataFrame 데이터를 기반으로 세로 막대�?또는 꺾은선형 차트와 같은 차트�?추가하여 추세�?비교�?시각화하�?�?도움�?�?�?있습니다.

Q5: DataFrame�?내보내려�?Microsoft Excel�?설치되어 있어�?하나�?

A5: 반드�?그렇지�?않습니다. Spire.XLS�?포함�?일부 라이브러리는 Excel 설치�?의존하지 않고 Python 내에�?전적으로 Excel 파일�?만들�?서식�?지정할 �?있습니다.

참고 항목

Figure 1 - Pandas DataFrame to Excel using Spire.XLS

Travailler avec des données tabulaires est une tâche courante pour les développeurs Python, et Pandas est la bibliothèque de référence pour la manipulation et l'analyse de données. Souvent, les développeurs ont besoin d'exporter des DataFrames Pandas vers Excel pour les rapports, la collaboration en équipe ou une analyse plus approfondie des données. Bien que Pandas fournisse la fonction to_excel pour les exportations de base, la création de rapports Excel professionnels avec des en-têtes formatés, des cellules stylisées, plusieurs feuilles et des graphiques peut être difficile.

Ce tutoriel montre comment écrire un seul DataFrame ou plusieurs DataFrames dans Excel en utilisant Spire.XLS for Python, une bibliothèque Excel multifonctionnelle qui permet une personnalisation complète des fichiers Excel directement depuis Python, sans qu'il soit nécessaire d'installer Microsoft Excel.

Table des matières

Pourquoi utiliser Spire.XLS pour convertir un DataFrame Pandas en Excel

Bien que Pandas offre une fonctionnalité d'exportation Excel de base, Spire.XLS étend cela en donnant un contrôle total sur la création de fichiers Excel. Au lieu de simplement écrire des données brutes, les développeurs peuvent :

  • Organiser plusieurs DataFrames dans des feuilles séparées au sein d'un même classeur.
  • Personnaliser les en-têtes, les polices, les couleurs et le formatage des cellules pour produire des mises en page professionnelles.
  • Ajuster automatiquement les colonnes et ajuster la hauteur des lignes pour une meilleure lisibilité.
  • Ajouter des graphiques, des formules et d'autres fonctionnalités Excel directement depuis Python

Prérequis pour convertir un DataFrame Pandas en Excel

Avant d'exporter un DataFrame Pandas vers Excel, assurez-vous d'avoir installé les bibliothèques requises suivantes. Vous pouvez le faire en exécutant la commande suivante dans le terminal de votre projet :

pip install pandas spire.xls

Ces bibliothèques vous permettent d'écrire des DataFrames dans Excel avec plusieurs feuilles, une mise en forme personnalisée, des graphiques attrayants et des mises en page structurées.

Exporter un seul DataFrame Pandas vers Excel avec mise en forme

L'exportation d'un seul DataFrame vers un fichier Excel est le scénario le plus courant. En utilisant Spire.XLS, vous pouvez non seulement exporter votre DataFrame, mais aussi formater les en-têtes, styliser les cellules et ajouter des graphiques pour donner à votre rapport un aspect professionnel.

Parcourons ce processus étape par étape.

Étape 1 : Créer un DataFrame d'exemple

Tout d'abord, nous devons créer un DataFrame. Ici, nous avons les noms des employés, les départements et les salaires. Vous pouvez, bien sûr, remplacer cela par votre propre jeu de données.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Étape 2 : Créer un classeur et accéder à la première feuille

Maintenant, nous allons créer un nouveau classeur Excel et préparer la première feuille de calcul. Donnons-lui un nom significatif pour qu'il soit facile à comprendre.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Étape 3 : Écrire les en-têtes de colonne

Nous écrirons les en-têtes sur la première ligne, les mettrons en gras et ajouterons un fond gris clair, pour que tout soit bien présenté.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Étape 4 : Écrire les lignes de données

Ensuite, nous écrivons chaque ligne du DataFrame. Pour les nombres, nous utilisons la propriété NumberValue afin qu'Excel puisse les reconnaître pour les calculs et les graphiques.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Étape 5 : Appliquer des bordures et ajuster automatiquement les colonnes

Pour donner à votre feuille Excel une apparence soignée, semblable à un tableau, ajoutons des bordures et ajustons automatiquement la largeur des colonnes.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Étape 6 : Ajouter un graphique pour visualiser les données

Les graphiques vous aident à comprendre rapidement les tendances. Ici, nous allons créer un histogramme comparant les salaires.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Étape 7 : Enregistrer le classeur

Enfin, enregistrez le classeur à l'emplacement de votre choix.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Résultat :

Le fichier Excel XLSX généré à partir du DataFrame Pandas ressemble à ceci :

Figure 2 - Single Pandas DataFrame to Excel with Formatting and Chart

Une fois le fichier Excel généré, il peut être traité ultérieurement, par exemple en le convertissant en PDF pour un partage facile :

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Pour plus de détails, consultez le guide sur la conversion d'Excel en PDF en Python.

Convertir plusieurs DataFrames Pandas en un seul fichier Excel

Lors de la création de rapports Excel, plusieurs jeux de données doivent souvent être placés sur des feuilles séparées. En utilisant Spire.XLS, chaque DataFrame Pandas peut être écrit sur sa propre feuille de calcul, garantissant que les données associées sont organisées de manière claire et faciles à analyser. Les étapes suivantes illustrent ce processus.

Étape 1 : Créer plusieurs DataFrames d'exemple

Avant l'exportation, nous créons deux DataFrames distincts - un pour les informations sur les employés et un autre pour les produits. Chaque DataFrame sera placé dans sa propre feuille Excel.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Ici, dataframes est une liste de tuples qui associe chaque DataFrame au nom de la feuille dans laquelle il doit apparaître.

Étape 2 : Créer un nouveau classeur

Ensuite, nous créons un nouveau classeur Excel pour stocker tous les DataFrames.

# Create a new workbook
workbook = Workbook()

Cela initialise un classeur vide avec trois feuilles par défaut. Nous les renommerons et les remplirons à l'étape suivante.

Étape 3 : Parcourir chaque DataFrame et l'écrire dans sa propre feuille

Au lieu d'écrire chaque DataFrame individuellement, nous pouvons parcourir notre liste et les traiter de la même manière. Cela réduit le code dupliqué et facilite la gestion de plus de jeux de données.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

En utilisant cette boucle, nous pouvons facilement ajouter plus de DataFrames à l'avenir sans réécrire le même code.

Étape 4 : Enregistrer le classeur

Enfin, nous enregistrons le fichier Excel. Les deux jeux de données sont maintenant soigneusement organisés dans un seul fichier avec des feuilles séparées, des en-têtes formatés et des bordures appropriées.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Votre fichier Excel est maintenant prêt à être partagé ou analysé plus en profondeur.

Résultat :

Figure 3 - Multiple Pandas DataFrames to Excel

Le fichier MultipleDataFrames.xlsx contient deux feuilles :

  • Employés (avec noms et âges)
  • Produits (avec détails et prix des produits)

Cette organisation rend les fichiers Excel multi-rapports propres et faciles à naviguer.

Écrire des DataFrames Pandas dans un fichier Excel existant

Dans certains cas, au lieu de créer un nouveau fichier Excel, vous devrez peut-être écrire des DataFrames dans un classeur existant. Cela peut être facilement réalisé en chargeant le classeur existant, en ajoutant une nouvelle feuille ou en accédant à la feuille souhaitée, et en écrivant les données du DataFrame en utilisant la même logique.

Le code suivant montre comment écrire un DataFrame Pandas dans un fichier Excel existant :

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Figure 4 - Write Pandas DataFrame to Existing Excel File

Personnalisation avancée pour l'exportation de DataFrames Pandas vers Excel

Au-delà des exportations de base, les DataFrames Pandas peuvent être personnalisés dans Excel pour répondre à des exigences de rapport spécifiques. Des options avancées, telles que la sélection de colonnes spécifiques et l'inclusion ou l'exclusion de l'index, vous permettent de créer des fichiers Excel plus propres, plus lisibles et professionnels. Les exemples suivants montrent comment appliquer ces personnalisations.

1. Sélectionner des colonnes spécifiques

Parfois, vous n'avez pas besoin d'exporter toutes les colonnes d'un DataFrame. En sélectionnant uniquement les colonnes pertinentes, vous pouvez garder vos rapports Excel concis et ciblés. Le code suivant montre comment parcourir les colonnes choisies lors de l'écriture des en-têtes et des lignes :

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Inclure ou exclure l'index

Par défaut, l'index du DataFrame n'est pas inclus dans l'exportation. Si votre rapport nécessite des identifiants de ligne ou des index numériques, vous pouvez les ajouter manuellement. Cet extrait de code montre comment inclure l'index à côté des colonnes sélectionnées :

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Conclusion

L'exportation d'un DataFrame Pandas vers Excel est simple, mais la production de rapports professionnels et bien formatés nécessite un contrôle supplémentaire. En utilisant Pandas pour la préparation des données et Spire.XLS for Python pour créer et formater des fichiers Excel, vous pouvez générer des classeurs structurés, lisibles et visuellement organisés. Cette approche fonctionne aussi bien pour les DataFrames uniques que pour les ensembles de données multiples, ce qui facilite la création de rapports Excel prêts pour l'analyse, le partage ou une manipulation ultérieure.

FAQ

Q1 : Comment puis-je exporter un DataFrame Pandas vers Excel en Python ?

R1 : Vous pouvez utiliser des bibliothèques comme Spire.XLS pour écrire un DataFrame dans un fichier Excel. Cela vous permet de transférer des données tabulaires de Python vers Excel tout en gardant le contrôle sur la mise en forme et la mise en page.

Q2 : Puis-je exporter plus d'un DataFrame dans un seul fichier Excel ?

R2 : Oui. Plusieurs DataFrames peuvent être écrits sur des feuilles séparées dans le même classeur. Cela aide à garder les ensembles de données associés organisés dans un seul fichier.

Q3 : Comment ajouter des en-têtes et formater des cellules dans Excel à partir d'un DataFrame ?

R3 : Les en-têtes peuvent être mis en gras, colorés ou avoir des largeurs fixes. Les valeurs numériques peuvent être stockées en tant que nombres et le texte en tant que chaînes de caractères. La mise en forme améliore la lisibilité des rapports.

Q4 : Est-il possible d'inclure des graphiques dans le fichier Excel exporté ?

R4 : Oui. Des graphiques tels que des histogrammes ou des graphiques linéaires peuvent être ajoutés en fonction des données de votre DataFrame pour aider à visualiser les tendances ou les comparaisons.

Q5 : Ai-je besoin d'avoir Microsoft Excel installé pour exporter des DataFrames ?

R5 : Pas nécessairement. Certaines bibliothèques, y compris Spire.XLS, peuvent créer et formater des fichiers Excel entièrement en Python sans dépendre de l'installation d'Excel.

Voir aussi

Figura 1 - DataFrame de Pandas a Excel usando Spire.XLS

Trabajar con datos tabulares es una tarea común para los desarrolladores de Python, y Pandas es la biblioteca de referencia para la manipulación y el análisis de datos. A menudo, los desarrolladores necesitan exportar DataFrames de Pandas a Excel para informes, colaboración en equipo o análisis de datos adicionales. Aunque Pandas proporciona la función to_excel para exportaciones básicas, crear informes de Excel profesionales con encabezados formateados, celdas con estilo, múltiples hojas y gráficos puede ser un desafío.

Este tutorial demuestra cómo escribir un único DataFrame o múltiples DataFrames en Excel usando Spire.XLS for Python, una biblioteca de Excel multifuncional que permite la personalización completa de archivos de Excel directamente desde Python, sin necesidad de tener Microsoft Excel instalado.

Tabla de Contenidos

Por qué usar Spire.XLS para exportar DataFrame de Pandas a Excel

Aunque Pandas proporciona una funcionalidad básica de exportación a Excel, Spire.XLS la amplía al dar un control total sobre la creación de archivos de Excel. En lugar de simplemente escribir datos sin procesar, los desarrolladores pueden:

  • Organizar múltiples DataFrames en hojas separadas dentro de un solo libro de trabajo.
  • Personalizar encabezados, fuentes, colores y formato de celdas para producir diseños profesionales.
  • Autoajustar columnas y ajustar la altura de las filas para mejorar la legibilidad.
  • Añadir gráficos, fórmulas y otras características de Excel directamente desde Python

Requisitos previos para exportar DataFrame de Pandas a Excel

Antes de exportar un DataFrame de Pandas a Excel, asegúrese de tener instaladas las siguientes bibliotecas requeridas. Puede hacerlo ejecutando el siguiente comando en la terminal de su proyecto:

pip install pandas spire.xls

Estas bibliotecas le permiten escribir DataFrames en Excel con múltiples hojas, formato personalizado, gráficos atractivos y diseños estructurados.

Exportar un único DataFrame de Pandas a Excel con formato

Exportar un único DataFrame a un archivo de Excel es el escenario más común. Usando Spire.XLS, no solo puede exportar su DataFrame, sino también formatear encabezados, aplicar estilo a las celdas y agregar gráficos para que su informe se vea profesional.

Repasemos este proceso paso a paso.

Paso 1: Crear un DataFrame de muestra

Primero, necesitamos crear un DataFrame. Aquí, tenemos nombres de empleados, departamentos y salarios. Por supuesto, puede reemplazar esto con su propio conjunto de datos.

import pandas as pd
from spire.xls import *

# Crear un DataFrame simple
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Paso 2: Crear un libro de trabajo y acceder a la primera hoja

Ahora crearemos un nuevo libro de trabajo de Excel y prepararemos la primera hoja de cálculo. Démosle un nombre significativo para que sea fácil de entender.

# Crear un nuevo libro de trabajo
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Datos de Empleados"

Paso 3: Escribir los encabezados de las columnas

Escribiremos los encabezados en la primera fila, los pondremos en negrita y agregaremos un fondo gris claro para que todo se vea ordenado.

# Escribir encabezados de columna
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Poner encabezados en negrita
    cell.Style.Color = Color.get_LightGray()     # Fondo gris claro

Paso 4: Escribir las filas de datos

A continuación, escribimos cada fila del DataFrame. Para los números, usamos la propiedad NumberValue para que Excel pueda reconocerlos para cálculos y gráficos.

# Escribir filas de datos
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Paso 5: Aplicar bordes y autoajustar columnas

Para darle a su hoja de Excel una apariencia pulida y similar a una tabla, agreguemos bordes y ajustemos automáticamente el ancho de las columnas.

# Aplicar bordes y autoajustar columnas
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Bordes exteriores
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Bordes interiores
usedRange.AutoFitColumns()

Paso 6: Agregar un gráfico para visualizar datos

Los gráficos le ayudan a comprender rápidamente las tendencias. Aquí, crearemos un gráfico de columnas para comparar los salarios.

# Agregar un gráfico
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Rango de datos para el gráfico
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Posición del gráfico
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Comparación de salarios de empleados"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Paso 7: Guardar el libro de trabajo

Finalmente, guarde el libro de trabajo en la ubicación deseada.

# Guardar el archivo de Excel
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Resultado:

El archivo XLSX de Excel generado a partir del DataFrame de Pandas se ve así:

Figura 2 - DataFrame de Pandas único a Excel con formato y gráfico

Una vez que se genera el archivo de Excel, se puede procesar más, como convertirlo a PDF para compartirlo fácilmente:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Para más detalles, consulte la guía sobre convertir Excel a PDF en Python.

Convertir múltiples DataFrames de Pandas a un solo archivo de Excel

Al crear informes de Excel, a menudo es necesario colocar múltiples conjuntos de datos en hojas separadas. Usando Spire.XLS, cada DataFrame de Pandas se puede escribir en su propia hoja de trabajo, asegurando que los datos relacionados estén organizados de forma clara y sean fáciles de analizar. Los siguientes pasos demuestran este flujo de trabajo.

Paso 1: Crear múltiples DataFrames de muestra

Antes de exportar, creamos dos DataFrames separados: uno para la información de los empleados y otro para los productos. Cada DataFrame irá a su propia hoja de Excel.

import pandas as pd
from spire.xls import *

# DataFrames de muestra
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# Lista de DataFrames con los nombres de hoja correspondientes
dataframes = [
    (df1, "Empleados"),
    (df2, "Productos")
]

Aquí, dataframes es una lista de tuplas que empareja cada DataFrame con el nombre de la hoja en la que debe aparecer.

Paso 2: Crear un nuevo libro de trabajo

A continuación, creamos un nuevo libro de trabajo de Excel para almacenar todos los DataFrames.

# Crear un nuevo libro de trabajo
workbook = Workbook()

Esto inicializa un libro de trabajo en blanco con tres hojas predeterminadas. Las renombraremos y poblaremos en el siguiente paso.

Paso 3: Recorrer cada DataFrame y escribirlo en su propia hoja

En lugar de escribir cada DataFrame individualmente, podemos recorrer nuestra lista y procesarlos de la misma manera. Esto reduce el código duplicado y facilita el manejo de más conjuntos de datos.

for i, (df, sheet_name) in enumerate(dataframes):
    # Obtener o crear una hoja
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Escribir encabezados con fuente en negrita y color de fondo
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Establecer ancho de columna fijo

    # Escribir filas de datos
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Aplicar bordes delgados alrededor del rango usado
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Bordes exteriores
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Bordes interiores

Usando este bucle, podemos agregar fácilmente más DataFrames en el futuro sin reescribir el mismo código.

Paso 4: Guardar el libro de trabajo

Finalmente, guardamos el archivo de Excel. Ambos conjuntos de datos ahora están organizados de forma ordenada en un solo archivo con hojas separadas, encabezados formateados y bordes adecuados.

# Guardar el libro de trabajo
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Ahora su archivo de Excel está listo para ser compartido o analizado más a fondo.

Resultado:

Figura 3 - Múltiples DataFrames de Pandas a Excel

El archivo MultipleDataFrames.xlsx contiene dos hojas:

  • Empleados (con nombres y edades)
  • Productos (con detalles de productos y precios)

Esta organización hace que los archivos de Excel con múltiples informes sean limpios y fáciles de navegar.

Escribir DataFrames de Pandas en un archivo de Excel existente

En algunos casos, en lugar de crear un nuevo archivo de Excel, es posible que necesite escribir DataFrames en un libro de trabajo existente. Esto se puede lograr fácilmente cargando el libro de trabajo existente, agregando una nueva hoja o accediendo a la hoja deseada y escribiendo los datos del DataFrame con la misma lógica.

El siguiente código muestra cómo escribir un DataFrame de Pandas en un archivo de Excel existente:

import pandas as pd
from spire.xls import *

# Cargar un archivo de Excel existente
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Crear un nuevo DataFrame para agregar
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Agregar una nueva hoja de trabajo para el nuevo DataFrame
new_sheet = workbook.Worksheets.Add("Ventas Regionales")

# Escribir encabezados
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Escribir filas de datos
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Guardar los cambios
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Figura 4 - Escribir DataFrame de Pandas en un archivo de Excel existente

Personalización avanzada para exportar DataFrames de Pandas a Excel

Más allá de las exportaciones básicas, los DataFrames de Pandas se pueden personalizar en Excel para cumplir con requisitos específicos de informes. Las opciones avanzadas, como seleccionar columnas específicas e incluir o excluir el índice, le permiten crear archivos de Excel más limpios, legibles y profesionales. Los siguientes ejemplos demuestran cómo aplicar estas personalizaciones.

1. Seleccionar columnas específicas

A veces, es posible que no necesite exportar todas las columnas de un DataFrame. Al seleccionar solo las columnas relevantes, puede mantener sus informes de Excel concisos y enfocados. El siguiente código demuestra cómo recorrer las columnas elegidas al escribir encabezados y filas:

import pandas as pd
from spire.xls import *

# Crear un DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Establecer las columnas a exportar
columns_to_export = ['Employee', 'Department']

# Crear un nuevo libro de trabajo y acceder a la primera hoja
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Escribir encabezados
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Escribir filas
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Guardar el archivo de Excel
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Incluir o excluir el índice

Por defecto, el índice del DataFrame no se incluye en la exportación. Si su informe requiere identificadores de fila o índices numéricos, puede agregarlos manualmente. Este fragmento de código muestra cómo incluir el índice junto con las columnas seleccionadas:

# Escribir encabezado para el índice
sheet.Range[1, 1].Text = "Index"

# Escribir valores de índice (numéricos)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Usar NumberValue para numéricos

# Escribir encabezados para otras columnas
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Escribir las filas de datos
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Guardar el libro de trabajo
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Conclusión

Exportar un DataFrame de Pandas a Excel es simple, pero producir informes profesionales y bien formateados requiere un control adicional. Al usar Pandas para la preparación de datos y Spire.XLS for Python para crear y formatear archivos de Excel, puede generar libros de trabajo estructurados, legibles y visualmente organizados. Este enfoque funciona tanto para DataFrames individuales como para múltiples conjuntos de datos, lo que facilita la creación de informes de Excel que están listos para el análisis, el uso compartido o la manipulación posterior.

Preguntas frecuentes

P1: ¿Cómo puedo exportar un DataFrame de Pandas a Excel en Python?

R1: Puede usar bibliotecas como Spire.XLS para escribir un DataFrame en un archivo de Excel. Esto le permite transferir datos tabulares de Python a Excel manteniendo el control sobre el formato y el diseño.

P2: ¿Puedo exportar más de un DataFrame a un solo archivo de Excel?

R2: Sí. Se pueden escribir múltiples DataFrames en hojas separadas dentro del mismo libro de trabajo. Esto ayuda a mantener organizados los conjuntos de datos relacionados en un solo archivo.

P3: ¿Cómo agrego encabezados y formato a las celdas en Excel desde un DataFrame?

R3: Los encabezados se pueden poner en negrita, colorear o tener anchos fijos. Los valores numéricos se pueden almacenar como números y el texto como cadenas. El formato mejora la legibilidad de los informes.

P4: ¿Es posible incluir gráficos en el archivo de Excel exportado?

R4: Sí. Se pueden agregar gráficos como los de columnas o líneas basados en los datos de su DataFrame para ayudar a visualizar tendencias o comparaciones.

P5: ¿Necesito tener Microsoft Excel instalado para exportar DataFrames?

R5: No necesariamente. Algunas bibliotecas, incluido Spire.XLS, pueden crear y formatear archivos de Excel completamente en Python sin depender de que Excel esté instalado.

Ver también

Abbildung 1 - Pandas DataFrame nach Excel mit Spire.XLS

Die Arbeit mit tabellarischen Daten ist eine häufige Aufgabe für Python-Entwickler, und Pandas ist die bevorzugte Bibliothek für die Datenmanipulation und -analyse. Oft müssen Entwickler Pandas DataFrames zur Berichterstellung, zur Zusammenarbeit im Team oder zur weiteren Datenanalyse nach Excel exportieren. Während Pandas die Funktion to_excel für grundlegende Exporte bereitstellt, kann die Erstellung professioneller Excel-Berichte mit formatierten Kopfzeilen, gestalteten Zellen, mehreren Blättern und Diagrammen eine Herausforderung sein.

Dieses Tutorial zeigt, wie man einen einzelnen DataFrame oder mehrere DataFrames nach Excel schreibt, indem man Spire.XLS for Python verwendet, eine multifunktionale Excel-Bibliothek, die eine vollständige Anpassung von Excel-Dateien direkt aus Python ermöglicht, ohne dass Microsoft Excel installiert sein muss.

Inhaltsverzeichnis

Warum Spire.XLS für Pandas DataFrame nach Excel verwenden

Während Pandas grundlegende Excel-Exportfunktionen bietet, erweitert Spire.XLS diese, indem es die volle Kontrolle über die Erstellung von Excel-Dateien gibt. Anstatt nur Rohdaten zu schreiben, können Entwickler:

  • Mehrere DataFrames in separaten Blättern innerhalb einer einzigen Arbeitsmappe organisieren.
  • Kopfzeilen, Schriftarten, Farben und Zellformatierungen anpassen, um professionelle Layouts zu erstellen.
  • Spalten automatisch anpassen und Zeilenhöhen für eine bessere Lesbarkeit einstellen.
  • Diagramme, Formeln und andere Excel-Funktionen direkt aus Python hinzufügen

Voraussetzungen für Pandas DataFrame nach Excel

Bevor Sie einen Pandas DataFrame nach Excel exportieren, stellen Sie sicher, dass Sie die folgenden erforderlichen Bibliotheken installiert haben. Sie können dies tun, indem Sie den folgenden Befehl im Terminal Ihres Projekts ausführen:

pip install pandas spire.xls

Diese Bibliotheken ermöglichen es Ihnen, DataFrames mit mehreren Blättern, benutzerdefinierter Formatierung, ansprechenden Diagrammen und strukturierten Layouts nach Excel zu schreiben.

Exportieren eines einzelnen Pandas DataFrame nach Excel mit Formatierung

Der Export eines einzelnen DataFrame in eine Excel-Datei ist das häufigste Szenario. Mit Spire.XLS können Sie nicht nur Ihren DataFrame exportieren, sondern auch Kopfzeilen formatieren, Zellen gestalten und Diagramme hinzufügen, um Ihren Bericht professionell aussehen zu lassen.

Lassen Sie uns diesen Prozess Schritt für Schritt durchgehen.

Schritt 1: Erstellen Sie einen Beispiel-DataFrame

Zuerst müssen wir einen DataFrame erstellen. Hier haben wir Mitarbeiternamen, Abteilungen und Gehälter. Sie können dies natürlich durch Ihren eigenen Datensatz ersetzen.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Schritt 2: Erstellen Sie eine Arbeitsmappe und greifen Sie auf das erste Blatt zu

Jetzt erstellen wir eine neue Excel-Arbeitsmappe und bereiten das erste Arbeitsblatt vor. Geben wir ihm einen aussagekräftigen Namen, damit es leicht verständlich ist.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Schritt 3: Spaltenüberschriften schreiben

Wir schreiben die Überschriften in die erste Zeile, machen sie fett und fügen einen hellgrauen Hintergrund hinzu, damit alles ordentlich aussieht.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Schritt 4: Datenzeilen schreiben

Als Nächstes schreiben wir jede Zeile aus dem DataFrame. Für Zahlen verwenden wir die NumberValue-Eigenschaft, damit Excel sie für Berechnungen und Diagramme erkennen kann.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Schritt 5: Rahmen anwenden und Spalten automatisch anpassen

Um Ihrem Excel-Blatt ein poliertes, tabellenähnliches Aussehen zu verleihen, fügen wir Rahmen hinzu und passen die Spaltenbreiten automatisch an.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Schritt 6: Fügen Sie ein Diagramm zur Visualisierung von Daten hinzu

Diagramme helfen Ihnen, Trends schnell zu verstehen. Hier erstellen wir ein Säulendiagramm zum Vergleich der Gehälter.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Schritt 7: Speichern der Arbeitsmappe

Speichern Sie abschließend die Arbeitsmappe an Ihrem gewünschten Ort.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Ergebnis:

Die aus dem Pandas DataFrame generierte Excel-XLSX-Datei sieht so aus:

Abbildung 2 - Einzelner Pandas DataFrame nach Excel mit Formatierung und Diagramm

Sobald die Excel-Datei generiert ist, kann sie weiterverarbeitet werden, z. B. in PDF konvertiert werden, um sie einfach zu teilen:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Weitere Einzelheiten finden Sie in der Anleitung zum Konvertieren von Excel in PDF in Python.

Konvertieren mehrerer Pandas DataFrames in eine Excel-Datei

Bei der Erstellung von Excel-Berichten müssen oft mehrere Datensätze auf separaten Blättern platziert werden. Mit Spire.XLS kann jeder Pandas DataFrame in sein eigenes Arbeitsblatt geschrieben werden, um sicherzustellen, dass zusammengehörige Daten klar organisiert und leicht zu analysieren sind. Die folgenden Schritte demonstrieren diesen Arbeitsablauf.

Schritt 1: Erstellen Sie mehrere Beispiel-DataFrames

Vor dem Exportieren erstellen wir zwei separate DataFrames - einen für Mitarbeiterinformationen und einen anderen für Produkte. Jeder DataFrame wird in sein eigenes Excel-Blatt eingefügt.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Hier ist dataframes eine Liste von Tupeln, die jeden DataFrame mit dem Namen des Blattes paart, in dem er erscheinen soll.

Schritt 2: Erstellen Sie eine neue Arbeitsmappe

Als Nächstes erstellen wir eine neue Excel-Arbeitsmappe, um alle DataFrames zu speichern.

# Create a new workbook
workbook = Workbook()

Dadurch wird eine leere Arbeitsmappe mit drei Standardblättern initialisiert. Wir werden sie im nächsten Schritt umbenennen und füllen.

Schritt 3: Durchlaufen Sie jeden DataFrame und schreiben Sie ihn in sein eigenes Blatt

Anstatt jeden DataFrame einzeln zu schreiben, können wir unsere Liste durchlaufen und sie auf die gleiche Weise verarbeiten. Dies reduziert doppelten Code und erleichtert die Handhabung von mehr Datensätzen.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

Mit dieser Schleife können wir in Zukunft problemlos weitere DataFrames hinzufügen, ohne denselben Code neu schreiben zu müssen.

Schritt 4: Speichern der Arbeitsmappe

Schließlich speichern wir die Excel-Datei. Beide Datensätze sind jetzt ordentlich in einer Datei mit separaten Blättern, formatierten Kopfzeilen und korrekten Rahmen organisiert.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Jetzt ist Ihre Excel-Datei bereit, geteilt oder weiter analysiert zu werden.

Ergebnis:

Abbildung 3 - Mehrere Pandas DataFrames nach Excel

Die Datei MultipleDataFrames.xlsx enthält zwei Blätter:

  • Mitarbeiter (mit Namen und Alter)
  • Produkte (mit Produktdetails und Preisen)

Diese Organisation macht Excel-Dateien mit mehreren Berichten sauber und einfach zu navigieren.

Schreiben von Pandas DataFrames in eine vorhandene Excel-Datei

In einigen Fällen müssen Sie möglicherweise DataFrames in eine vorhandene Arbeitsmappe schreiben, anstatt eine neue Excel-Datei zu erstellen. Dies kann einfach erreicht werden, indem Sie die vorhandene Arbeitsmappe laden, ein neues Blatt hinzufügen oder auf das gewünschte Blatt zugreifen und die DataFrame-Daten mit derselben Logik schreiben.

Der folgende Code zeigt, wie man einen Pandas DataFrame in eine vorhandene Excel-Datei schreibt:

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Abbildung 4 - Pandas DataFrame in eine vorhandene Excel-Datei schreiben

Erweiterte Anpassung für den Export von Pandas DataFrames nach Excel

Über grundlegende Exporte hinaus können Pandas DataFrames in Excel angepasst werden, um spezifische Berichtsanforderungen zu erfüllen. Erweiterte Optionen �?wie die Auswahl bestimmter Spalten und das Ein- oder Ausschließen des Index �?ermöglichen es Ihnen, sauberere, besser lesbare und professionellere Excel-Dateien zu erstellen. Die folgenden Beispiele zeigen, wie diese Anpassungen angewendet werden.

1. Bestimmte Spalten auswählen

Manchmal müssen Sie möglicherweise nicht alle Spalten aus einem DataFrame exportieren. Indem Sie nur die relevanten Spalten auswählen, können Sie Ihre Excel-Berichte prägnant und fokussiert halten. Der folgende Code zeigt, wie Sie beim Schreiben von Kopf- und Datenzeilen durch ausgewählte Spalten iterieren:

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Index ein- oder ausschließen

Standardmäßig wird der DataFrame-Index nicht in den Export einbezogen. Wenn Ihr Bericht Zeilenkennungen oder numerische Indizes erfordert, können Sie diese manuell hinzufügen. Dieses Code-Snippet zeigt, wie Sie den Index neben ausgewählten Spalten einfügen:

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Fazit

Das Exportieren eines Pandas DataFrame nach Excel ist einfach, aber die Erstellung professioneller, gut formatierter Berichte erfordert zusätzliche Kontrolle. Durch die Verwendung von Pandas zur Datenvorbereitung und Spire.XLS for Python zum Erstellen und Formatieren von Excel-Dateien können Sie strukturierte, lesbare und visuell organisierte Arbeitsmappen erstellen. Dieser Ansatz funktioniert sowohl für einzelne DataFrames als auch für mehrere Datensätze und erleichtert die Erstellung von Excel-Berichten, die für die Analyse, den Austausch oder die weitere Bearbeitung bereit sind.

Häufig gestellte Fragen

F1: Wie kann ich einen Pandas DataFrame in Python nach Excel exportieren?

A1: Sie können Bibliotheken wie Spire.XLS verwenden, um einen DataFrame in eine Excel-Datei zu schreiben. Dies ermöglicht es Ihnen, tabellarische Daten von Python nach Excel zu übertragen und dabei die Kontrolle über Formatierung und Layout zu behalten.

F2: Kann ich mehr als einen DataFrame in eine einzelne Excel-Datei exportieren?

A2: Ja. Mehrere DataFrames können in separate Blätter innerhalb derselben Arbeitsmappe geschrieben werden. Dies hilft, zusammengehörige Datensätze in einer Datei organisiert zu halten.

F3: Wie füge ich Kopfzeilen hinzu und formatiere Zellen in Excel aus einem DataFrame?

A3: Kopfzeilen können fett, farbig oder mit fester Breite formatiert werden. Numerische Werte können als Zahlen und Text als Zeichenfolgen gespeichert werden. Die Formatierung verbessert die Lesbarkeit von Berichten.

F4: Ist es möglich, Diagramme in die exportierte Excel-Datei aufzunehmen?

A4: Ja. Diagramme wie Säulen- oder Liniendiagramme können basierend auf Ihren DataFrame-Daten hinzugefügt werden, um Trends oder Vergleiche zu visualisieren.

F5: Benötige ich eine installierte Microsoft Excel-Version, um DataFrames zu exportieren?

A5: Nicht unbedingt. Einige Bibliotheken, einschließlich Spire.XLS, können Excel-Dateien vollständig in Python erstellen und formatieren, ohne dass Excel installiert sein muss.

Siehe auch

Рисунок 1 - DataFrame Pandas в Excel с использованием Spire.XLS

Работа с табличными данными �?обычная задача для разработчиков на Python, и Pandas является основной библиотекой для обработки и анализа данных. Часто разработчикам необходимо экспортировать DataFrame Pandas в Excel для отчетности, совместной работы в команде или дальнейшего анализа данных. Хотя Pandas предоставляет функцию to_excel для базового экспорта, создание профессиональных отчетов Excel с отформатированными заголовками, стилизованными ячейками, несколькими листами и диаграммами может быть сложной задачей.

В этом руководстве показано, как записать один или несколько DataFrame в Excel с использованием Spire.XLS for Python, многофункциональной библиотеки Excel, которая позволяет полностью настраивать файлы Excel непосредственно из Python без необходимости установки Microsoft Excel.

Содержание

Зачем использовать Spire.XLS для преобразования DataFrame Pandas в Excel

Хотя Pandas предоставляет базовые функции экспорта в Excel, Spire.XLS расширяет их, предоставляя полный контроль над созданием файлов Excel. Вместо того, чтобы просто записывать необработанные данные, разработчики могут:

  • Организовывать несколько DataFrame на отдельных листах в одной рабочей книге.
  • Настраивать заголовки, шрифты, цвета и форматирование ячеек для создания профессиональных макетов.
  • Автоподбор ширины столбцов и настраивать высоту строк для улучшения читаемости.
  • Добавлять диаграммы, формулы и другие функции Excel непосредственно из Python

Предварительные требования для преобразования DataFrame Pandas в Excel

Перед экспортом DataFrame Pandas в Excel убедитесь, что у вас установлены следующие необходимые библиотеки. Вы можете сделать это, выполнив следующую команду в терминале вашего проекта:

pip install pandas spire.xls

Эти библиотеки позволяют записывать DataFrame в Excel с несколькими листами, настраиваемым форматированием, привлекательными диаграммами и структурированными макетами.

Экспорт одного DataFrame Pandas в Excel с форматированием

Экспорт одного DataFrame в файл Excel �?наиболее распространенный сценарий. Используя Spire.XLS, вы можете не только экспортировать свой DataFrame, но и форматировать заголовки, стилизовать ячейки и добавлять диаграммы, чтобы ваш отчет выглядел профессионально.

Давайте пройдем этот процесс шаг за шагом.

Шаг 1: Создайте образец DataFrame

Сначала нам нужно создать DataFrame. Здесь у нас есть имена сотрудников, отделы и зарплаты. Вы, конечно, можете заменить это своим собственным набором данных.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Шаг 2: Создайте рабочую книгу и получите доступ к первому листу

Теперь мы создадим новую рабочую книгу Excel и подготовим первый рабочий лист. Давайте дадим ему осмысленное имя, чтобы его было легко понять.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Шаг 3: Запишите заголовки столбцов

Мы запишем заголовки в первую строку, сделаем их жирными и добавим светло-серый фон, чтобы все выглядело аккуратно.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Шаг 4: Запишите строки данных

Далее мы записываем каждую строку из DataFrame. Для чисел мы используем свойство NumberValue, чтобы Excel мог распознавать их для вычислений и диаграмм.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Шаг 5: Примените границы и автоподбор ширины столбцов

Чтобы придать вашему листу Excel отполированный, табличный вид, давайте добавим границы и автоматически настроим ширину столбцов.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Шаг 6: Добавьте диаграмму для визуализации данных

Диаграммы помогают быстро понять тенденции. Здесь мы создадим гистограмму, сравнивающую зарплаты.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Шаг 7: Сохраните рабочую книгу

Наконец, сохраните рабочую книгу в нужном месте.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Результат:

Файл Excel XLSX, созданный из DataFrame Pandas, выглядит следующим образом:

Рисунок 2 - Один DataFrame Pandas в Excel с форматированием и диаграммой

После создания файла Excel его можно дополнительно обработать, например, преобразовать в PDF для удобного обмена:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

Для получения дополнительной информации см. руководство по преобразованию Excel в PDF на Python.

Преобразование нескольких DataFrame Pandas в один файл Excel

При создании отчетов Excel часто требуется размещать несколько наборов данных на отдельных листах. Используя Spire.XLS, каждый DataFrame Pandas можно записать на свой собственный рабочий лист, обеспечивая четкую организацию и легкий анализ связанных данных. Следующие шаги демонстрируют этот рабочий процесс.

Шаг 1: Создайте несколько образцов DataFrame

Перед экспортом мы создаем два отдельных DataFrame �?один для информации о сотрудниках, а другой для продуктов. Каждый DataFrame будет помещен на свой собственный лист Excel.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Здесь, dataframes �?это список кортежей, который сопоставляет каждый DataFrame с именем листа, на котором он должен появиться.

Шаг 2: Создайте новую рабочую книгу

Далее мы создаем новую рабочую книгу Excel для хранения всех DataFrame.

# Create a new workbook
workbook = Workbook()

Это инициализирует пустую рабочую книгу с тремя листами по умолчанию. Мы переименуем и заполним их на следующем шаге.

Шаг 3: Пройдитесь по каждому DataFrame и запишите его на свой лист

Вместо того, чтобы записывать каждый DataFrame по отдельности, мы можем пройтись по нашему списку и обработать их одинаково. Это уменьшает дублирование кода и упрощает обработку большего количества наборов данных.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

Используя этот цикл, мы можем легко добавлять больше DataFrame в будущем, не переписывая тот же код.

Шаг 4: Сохраните рабочую книгу

Наконец, мы сохраняем файл Excel. Оба набора данных теперь аккуратно организованы в одном файле с отдельными листами, отформатированными заголовками и правильными границами.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Теперь ваш файл Excel готов к совместному использованию или дальнейшему анализу.

Результат:

Рисунок 3 - Несколько DataFrame Pandas в Excel

Файл MultipleDataFrames.xlsx содержит два листа:

  • Сотрудники (с именами и возрастом)
  • Продукты (с деталями и ценами на продукты)

Такая организация делает многостраничные файлы Excel чистыми и удобными для навигации.

Запись DataFrame Pandas в существующий файл Excel

В некоторых случаях вместо создания нового файла Excel может потребоваться записать DataFrame в существующую рабочую книгу. Этого можно легко достичь, загрузив существующую рабочую книгу, добавив новый лист или получив доступ к нужному листу и записав данные DataFrame, используя ту же логику.

Следующий код показывает, как записать DataFrame Pandas в существующий файл Excel:

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Рисунок 4 - Запись DataFrame Pandas в существующий файл Excel

Расширенная настройка для экспорта DataFrame Pandas в Excel

Помимо базового экспорта, DataFrame Pandas можно настраивать в Excel для удовлетворения конкретных требований к отчетности. Расширенные параметры, такие как выбор определенных столбцов и включение или исключение индекса, позволяют создавать более чистые, читаемые и профессиональные файлы Excel. Следующие примеры демонстрируют, как применять эти настройки.

1. Выберите определенные столбцы

Иногда может не потребоваться экспортировать все столбцы из DataFrame. Выбирая только релевантные столбцы, вы можете сделать свои отчеты Excel краткими и сфокусированными. Следующий код демонстрирует, как перебирать выбранные столбцы при записи заголовков и строк:

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Включить или исключить индекс

По умолчанию индекс DataFrame не включается в экспорт. Если для вашего отчета требуются идентификаторы строк или числовые индексы, вы можете добавить их вручную. Этот фрагмент кода показывает, как включить индекс вместе с выбранными столбцами:

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Заключение

Экспорт DataFrame Pandas в Excel прост, но создание профессиональных, хорошо отформатированных отчетов требует дополнительного контроля. Используя Pandas для подготовки данных и Spire.XLS for Python для создания и форматирования файлов Excel, вы можете создавать структурированные, читаемые и визуально организованные рабочие книги. Этот подход работает как для отдельных DataFrame, так и для нескольких наборов данных, что упрощает создание отчетов Excel, готовых к анализу, совместному использованию или дальнейшей обработке.

Часто задаваемые вопросы

В1: Как я могу экспортировать DataFrame Pandas в Excel на Python?

О1: Вы можете использовать библиотеки, такие как Spire.XLS, для записи DataFrame в файл Excel. Это позволяет переносить табличные данные из Python в Excel, сохраняя контроль над форматированием и макетом.

В2: Могу ли я экспортировать более одного DataFrame в один файл Excel?

О2: Да. Несколько DataFrame можно записать на отдельные листы в одной рабочей книге. Это помогает хранить связанные наборы данных в одном файле.

В3: Как добавить заголовки и отформатировать ячейки в Excel из DataFrame?

О3: Заголовки можно сделать жирными, цветными или с фиксированной шириной. Числовые значения могут храниться как числа, а текст �?как строки. Форматирование улучшает читаемость отчетов.

В4: Возможно ли включить диаграммы в экспортированный файл Excel?

О4: Да. Диаграммы, такие как гистограммы или линейные диаграммы, могут быть добавлены на основе данных вашего DataFrame для визуализации тенденций или сравнений.

В5: Нужно ли мне устанавливать Microsoft Excel для экспорта DataFrame?

О5: Не обязательно. Некоторые библиотеки, включая Spire.XLS, могут создавать и форматировать файлы Excel полностью в Python, не требуя установки Excel.

Смотрите также

Figure 1 - Pandas DataFrame to Excel using Spire.XLS

Working with tabular data is a common task for Python developers, and Pandas is the go-to library for data manipulation and analysis. Often, developers need to export Pandas DataFrames to Excel for reporting, team collaboration, or further data analysis. While Pandas provides the to_excel function for basic exports, creating professional Excel reports with formatted headers, styled cells, multiple sheets, and charts can be challenging.

This tutorial demonstrates how to write a single DataFrame or multiple DataFrames to Excel using Spire.XLS for Python, a multi-functional Excel library that enables full customization of Excel files directly from Python-without needing Microsoft Excel to be installed.

Table of Contents

Why Use Spire.XLS for Pandas DataFrame to Excel

While Pandas provides basic Excel export functionality, Spire.XLS extends this by giving full control over Excel file creation. Instead of just writing raw data, developers can:

  • Organize multiple DataFrames into separate sheets within a single workbook.
  • Customize headers, fonts, colors, and cell formatting to produce professional layouts.
  • Auto-fit columns and adjust row heights for improved readability.
  • Add charts, formulas, and other Excel features directly from Python

Prerequisites for Pandas DataFrame to Excel

Before exporting a Pandas DataFrame to Excel, ensure you have the following required libraries installed. You can do this by running the following command in your project's terminal:

pip install pandas spire.xls

These libraries allow you to write DataFrames to Excel with multiple sheets, custom formatting, attractive charts, and structured layouts.

Export a Single Pandas DataFrame to Excel with Formatting

Exporting a single DataFrame to an Excel file is the most common scenario. Using Spire.XLS, you can not only export your DataFrame but also format headers, style cells, and add charts to make your report look professional.

Let's go through this process step by step.

Step 1: Create a Sample DataFrame

First, we need to create a DataFrame. Here, we have employee names, departments, and salaries. You can, of course, replace this with your own dataset.

import pandas as pd
from spire.xls import *

# Create a simple DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

Step 2: Create a Workbook and Access the First Sheet

Now we'll create a new Excel workbook and get the first worksheet ready. Let's give it a meaningful name so it's easy to understand.

# Create a new workbook
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Employee Data"

Step 3: Write Column Headers

We'll write the headers to the first row, make them bold and add a light gray background, so everything looks neat.

# Write column headers
for colIndex, colName in enumerate(df.columns, start=1):
    cell = sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True                # Make headers bold
    cell.Style.Color = Color.get_LightGray()     # Light gray background

Step 4: Write the Data Rows

Next, we write each row from the DataFrame. For numbers, we use the NumberValue property so Excel can recognize them for calculations and charts.

# Write data rows
for rowIndex, row in enumerate(df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

Step 5: Apply Borders and Auto-Fit Columns

To give your Excel sheet a polished, table-like appearance, let's add borders and automatically adjust the column widths.

# Apply borders and auto-fit columns
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders
usedRange.AutoFitColumns()

Step 6: Add a Chart to Visualize Data

Charts help you quickly understand trends. Here, we'll create a column chart comparing salaries.

# Add a chart
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered
chart.DataRange = sheet.Range["A1:C4"]        # Data range for chart
chart.SeriesDataFromRange = False
chart.LeftColumn = 5                          # Chart position
chart.TopRow = 1
chart.RightColumn = 10
chart.BottomRow = 16
chart.ChartTitle = "Employee Salary Comparison"
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True

Step 7: Save the Workbook

Finally, save the workbook to your desired location.

# Save the Excel file
workbook.SaveToFile("DataFrameWithChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Result:

The Excel XLSX File generated from Pandas DataFrame looks like this:

Figure 2 - Single Pandas DataFrame to Excel with Formatting and Chart

Once the Excel file is generated, it can be further processed, such as being converted to PDF for easy sharing:

workbook.SaveToFile("ToPdf.pdf", FileFormat.PDF)

For more details, see the guide on converting Excel to PDF in Python.

Convert Multiple Pandas DataFrames to One Excel File

When creating Excel reports, multiple datasets often need to be placed on separate sheets. Using Spire.XLS, each Pandas DataFrame can be written to its own worksheet, ensuring related data is organized clearly and easy to analyze. The following steps demonstrate this workflow.

Step 1: Create Multiple Sample DataFrames

Before exporting, we create two separate DataFrames - one for employee information and another for products. Each DataFrame will go into its own Excel sheet.

import pandas as pd
from spire.xls import *

# Sample DataFrames
df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df2 = pd.DataFrame({'Product': ['Laptop', 'Phone'], 'Price': [1000, 500]})

# List of DataFrames with corresponding sheet names
dataframes = [
    (df1, "Employees"),
    (df2, "Products")
]

Here, dataframes is a list of tuples that pairs each DataFrame with the name of the sheet it should appear in.

Step 2: Create a New Workbook

Next, we create a new Excel workbook to store all the DataFrames.

# Create a new workbook
workbook = Workbook()

This initializes a blank workbook with three default sheets. We'll rename and populate them in the next step.

Step 3: Loop Through Each DataFrame and Write to Its Own Sheet

Instead of writing each DataFrame individually, we can loop through our list and process them in the same way. This reduces duplicate code and makes it easier to handle more datasets.

for i, (df, sheet_name) in enumerate(dataframes):
    # Get or create a sheet
    if i < workbook.Worksheets.Count:
        sheet = workbook.Worksheets[i]
    else:
        sheet = workbook.Worksheets.Add()

    sheet.Name = sheet_name

    # Write headers with bold font and background color
    for colIndex, colName in enumerate(df.columns, start=1):
        cell = sheet.Range[1, colIndex]
        cell.Text = colName
        cell.Style.Font.IsBold = True
        cell.Style.Color = Color.get_LightGray()
        sheet.Columns[colIndex - 1].ColumnWidth = 15  # Set fixed column width

    # Write rows of data
    for rowIndex, row in enumerate(df.values, start=2):
        for colIndex, value in enumerate(row, start=1):
            cell = sheet.Range[rowIndex, colIndex]
            if isinstance(value, (int, float)):
                cell.NumberValue = value
            else:
                cell.Text = str(value)

    # Apply thin borders around the used range
    usedRange = sheet.AllocatedRange
    usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # Outside borders
    usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # Inside borders

Using this loop, we can easily add more DataFrames in the future without rewriting the same code.

Step 4: Save the Workbook

Finally, we save the Excel file. Both datasets are now neatly organized in one file with separate sheets, formatted headers, and proper borders.

# Save the workbook
workbook.SaveToFile("MultipleDataFrames.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Now your Excel file is ready to be shared or analyzed further.

Result:

Figure 3 - Multiple Pandas DataFrames to Excel

The file MultipleDataFrames.xlsx contains two sheets:

  • Employees (with names and ages)
  • Products (with product details and prices)

This organization makes multi-report Excel files clean and easy to navigate.

Write Pandas DataFrames to Existing Excel File

In some cases, instead of creating a new Excel file, you may need to write DataFrames to an existing workbook. This can be easily achieved by loading the existing workbook, adding a new sheet or accessing the desired sheet, and writing the DataFrame data using the same logic.

The following code shows how to write a Pandas DataFrame to an Existing Excel file:

import pandas as pd
from spire.xls import *

# Load an existing Excel file
workbook = Workbook()
workbook.LoadFromFile("MultipleDataFrames.xlsx")

# Create a new DataFrame to add
new_df = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West'],
    'Sales': [12000, 15000, 13000, 11000]
})

# Add a new worksheet for the new DataFrame
new_sheet = workbook.Worksheets.Add("Regional Sales")

# Write headers
for colIndex, colName in enumerate(new_df.columns, start=1):
    cell = new_sheet.Range[1, colIndex]
    cell.Text = colName
    cell.Style.Font.IsBold = True
    cell.Style.Color = Color.get_LightGray()
    new_sheet.Columns[colIndex - 1].ColumnWidth = 15

# Write data rows
for rowIndex, row in enumerate(new_df.values, start=2):
    for colIndex, value in enumerate(row, start=1):
        cell = new_sheet.Range[rowIndex, colIndex]
        if isinstance(value, (int, float)):
            cell.NumberValue = value
        else:
            cell.Text = str(value)

# Save the changes
workbook.SaveToFile("DataFrameToExistingWorkbook.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Figure 4 - Write Pandas DataFrame to Existing Excel File

Advanced Customization for Exporting Pandas DataFrames to Excel

Beyond basic exports, Pandas DataFrames can be customized in Excel to meet specific reporting requirements. Advanced options-such as selecting specific columns, and including or excluding the index-allow you to create cleaner, more readable, and professional Excel files. The following examples demonstrate how to apply these customizations.

1. Select Specific Columns

Sometimes you may not need to export all columns from a DataFrame. By selecting only the relevant columns, you can keep your Excel reports concise and focused. The following code demonstrates how to loop through chosen columns when writing headers and rows:

import pandas as pd
from spire.xls import *

# Create a DataFrame
df = pd.DataFrame({
    'Employee': ['Alice', 'Bob', 'Charlie'],
    'Department': ['HR', 'Finance', 'IT'],
    'Salary': [5000, 6000, 7000]
})

# Set the columns to export
columns_to_export = ['Employee', 'Department']

# Create a new workbook and access the first sheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers
for colIndex, colName in enumerate(columns_to_export, start=1):
    sheet.Range[1, colIndex].Text = colName

# Write rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=1):
        sheet.Range[rowIndex, colIndex].Text = value

# Save the Excel file
workbook.SaveToFile("select_columns.xlsx")
workbook.Dispose()

2. Include or Exclude Index

By default, the DataFrame index is not included in the export. If your report requires row identifiers or numeric indices, you can add them manually. This code snippet shows how to include the index alongside selected columns:

# Write header for index
sheet.Range[1, 1].Text = "Index"

# Write index values (numeric)
for rowIndex, idx in enumerate(df.index, start=2):
    sheet.Range[rowIndex, 1].NumberValue = idx  # Use NumberValue for numeric

# Write headers for other columns
for colIndex, colName in enumerate(columns_to_export, start=2):
    sheet.Range[1, colIndex].Text = colName

# Write the data rows
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
    for colIndex, value in enumerate(row, start=2):
        if isinstance(value, (int, float)):
            sheet.Range[rowIndex, colIndex].NumberValue = value
        else:
            sheet.Range[rowIndex, colIndex].Text = str(value)

# Save the workbook
workbook.SaveToFile("include_index.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Conclusion

Exporting a Pandas DataFrame to Excel is simple, but producing professional, well-formatted reports requires additional control. By using Pandas for data preparation and Spire.XLS for Python to create and format Excel files, you can generate structured, readable, and visually organized workbooks. This approach works for both single DataFrames and multiple datasets, making it easy to create Excel reports that are ready for analysis, sharing, or further manipulation.

FAQs

Q1: How can I export a Pandas DataFrame to Excel in Python?

A1: You can use libraries like Spire.XLS to write a DataFrame to an Excel file. This allows you to transfer tabular data from Python into Excel while keeping control over formatting and layout.

Q2: Can I export more than one DataFrame to a single Excel file?

A2: Yes. Multiple DataFrames can be written to separate sheets within the same workbook. This helps keep related datasets organized in one file.

Q3: How do I add headers and format cells in Excel from a DataFrame?

A3: Headers can be made bold, colored, or have fixed widths. Numeric values can be stored as numbers and text as strings. Formatting improves readability for reports.

Q4: Is it possible to include charts in the exported Excel file?

A4: Yes. Charts such as column or line charts can be added based on your DataFrame data to help visualize trends or comparisons.

Q5: Do I need Microsoft Excel installed to export DataFrames?

A5: Not necessarily. Some libraries, including Spire.XLS, can create and format Excel files entirely within Python without relying on Excel being installed.

See Also

Install with Pypi

pip install spire.presentation

How to Create a Pie Chart in PowerPoint Presentation

Making your data easy to understand can be tricky, especially if you’re not sure how to turn numbers into visuals. If you’ve ever opened PowerPoint and wondered how to make a chart quickly, you’re in the right place. In this guide, you’ll learn how to create a pie chart in PowerPoint, step by step. We’ll cover everything from adding a chart to customizing colors and labels, so your slides look clear and professional. By the end, you’ll be able to show your data in a way that’s simple, attractive, and easy for anyone to understand.

How to Create a Pie Chart in PowerPoint Manually

Making a pie chart in PowerPoint is easier than you might think. In this chapter, we’ll guide you step by step through the process. First, make sure you have your data ready along with a PowerPoint presentation. Most importantly, you’ll need Microsoft PowerPoint or another presentation editing app installed on your device. In this tutorial, we’ll use Microsoft PowerPoint as our example. Once you’re ready, let’s dive into today’s guide.

Step 1: Open Your Presentation

Start by locating and opening the PowerPoint file where you want to add your chart.

Step 2: Choose the Slide

Select the slide where the pie chart should appear. Make sure it’s ready for the data you want to show.

Step 3: Insert the Chart

Go to the Insert tab on the Ribbon at the top and click Chart.

Step 4: Pick Your Pie Chart

In the Insert Chart dialog box, select Pie from the left panel. You’ll see several types of pie charts—if you want to create a 3D Pie chart on the slide, choose the second option. Click OK to insert the chart.

Create a Pie Chart in PowerPoint Presentation Manually

Step 5: Enter Your Data

PowerPoint will show default data in an Excel-like sheet. Replace it with your own numbers to match your presentation needs.

Edit Data

Step 6: Customize the Chart

Click the chart and go to the Chart Design tab on the Ribbon. Here, you can change the style, colors, labels, or even switch to another chart type. Play around until it looks just right for your slide.

Here is the final look of the pie chart: The Pie Chart Created in Microsoft PowerPoint

How to Create a Pie Chart in PowerPoint Presentation Automatically

After learning how to add a pie chart manually in PowerPoint, you’ve probably noticed that the steps can be a bit tedious, especially when updating data or customizing the chart. So, is there a faster way?

Using code to generate charts is a great solution. With Spire.Presentation, a professional PowerPoint library, you can easily create charts automatically, handling everything from file setup to data input and chart customization in one go.

Here’s a detailed guide on how to create a chart in PowerPoint using Spire.Presentation:

Step 1: Install Spire.Presentation

In this tutorial, we’ll use Spire.Presentation for Python. You can install it via pip by opening your Python environment (for example, the VSCode terminal) and running:

pip install spire.presentation

Press Enter, and the library will be installed.

Step 2: Write the Code

Here’s the overall logic for creating a pie chart with Spire.Presentation:

  • Import the file – Load the PowerPoint presentation you want to work with or create a new presentation.
  • Access the target slide – Select the slide where the pie chart will be inserted.
  • Insert the pie chart – Add a pie chart object to the slide.
  • Set the chart title – Give your pie chart a title.
  • Add data to the chart – Fill the pie chart with your dataset.
  • Customize chart colors – Adjust colors to make the chart visually appealing.

Below is the complete Python code showing how to create a pie chart while making a new PowerPoint presentation:

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation instance
presentation = Presentation()

# Add a pie chart at a specified location on the first slide
rect = RectangleF.FromLTRB (40, 100, 590, 420)
chart = presentation.Slides[0].Shapes.AppendChartInit (ChartType.Pie, rect, False)

# Set and format chart title
chart.ChartTitle.TextProperties.Text = "Sales by Quarter (2024)"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30
chart.HasTitle = True

# Define some data
quarters = ["1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr"]
sales = [210, 320, 180, 460]

# Append data to ChartData, which represents a data table where the chart data is stored
chart.ChartData[0,0].Text = "Quarters"
chart.ChartData[0,1].Text = "Sales"
i = 0
while i < len(quarters):
    chart.ChartData[i + 1,0].Text = quarters[i]
    chart.ChartData[i + 1,1].NumberValue = sales[i]
    i += 1

# Set series labels and category labels
chart.Series.SeriesLabel = chart.ChartData["B1","B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

# Set values for series
chart.Series[0].Values = chart.ChartData["B2","B5"]

# Add data points to series
for i, unusedItem in enumerate(chart.Series[0].Values):
    cdp = ChartDataPoint(chart.Series[0])
    cdp.Index = i
    chart.Series[0].DataPoints.Add(cdp)

# Fill each data point with a different color
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_Honeydew()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_LightPink()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_AliceBlue()

# Set the data labels to display label value and percentage value
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True

# Save the result file
presentation.SaveToFile("E:/Administrator/Python1/output/CreatePieChart.pptx", FileFormat.Pptx2016)
presentation.Dispose()

Here's the pie chart made by Spire.Presentation:

Create a Pie Chart in PowerPoint Presentation with Spire.Presentation

With Spire.Presentation, you can do much more than just create pie charts. It also lets you generate column charts, line charts, bar charts, and many other types of visuals directly in your slides. Plus, the library supports multiple programming languages — whether you prefer C#, Java, Python or JavaScript, you can easily create and customize charts with just a few lines of code.

The Conclusion

In this guide, we’ve walked through how to create a pie chart in PowerPoint step by step, from inserting the chart manually to customizing its style and colors. While the manual method works well for simple tasks, Spire.Presentation works better under complecated situations. With this professional library, you can automate the entire process—from adding charts and inputting data to customizing their appearance. Try it out immediately by obtaining a temporary license for 30 days , making chart creation faster and more efficient than ever.

FAQs about Creating a Pie Chart in PowerPoint

1. How do I create a pie chart step by step in PowerPoint?

Go to Insert → Chart → Pie, then replace the sample data with your own and adjust the chart style under Chart Design.

2. How can I show percentages in a pie chart?

Click the chart, select Data Labels → More Options, and check Percentage to display values as percentages.

3. How do I make a progress pie chart in PowerPoint?

Use a Pie or Doughnut chart with two values—progress and remaining—and format the slices with different colors.

4. Can I automate pie chart creation?

Yes. You can use Spire.Presentation to generate and edit charts automatically after obtaining a temporary license.


ALSO READ