Cuando necesites convertir un archivo de Excel a PDF, puedes utilizar el lenguaje de programación Python y algunas bibliotecas populares para esta tarea. En esta publicación de blog, describiré cómo crear una herramienta de interfaz gráfica de usuario (GUI) fácil de usar para hacer el trabajo usando wxPython, pandas y la biblioteca PyMuPDF.
C:\pythoncode\new\excelexportpdf.py
Preparación
Antes de comenzar, asegúrese de haber instalado Python y las siguientes bibliotecas requeridas:
- wxPython: se utiliza para crear interfaces GUI.
- pandas: utilizado para leer datos de archivos de Excel.
- PyMuPDF: Se utiliza para exportar datos como archivos PDF.
Puede utilizar la herramienta pip para instalar estas bibliotecas:
pip install wxPython pandas PyMuPDF
Crear una interfaz GUI
Usaremos la biblioteca wxPython para construir la interfaz de usuario. Primero, importe las bibliotecas requeridas:
import wx
import pandas as pd
import fitz
A continuación, crearemos una ExcelToPDFFrame
clase llamada, que hereda de wx.Frame
la clase. Esta clase representará nuestra ventana principal:
class ExcelToPDFFrame(wx.Frame):
def __init__(self, parent, title):
super(ExcelToPDFFrame, self).__init__(parent, title=title, size=(400, 200))
En __init__
el método, configuramos el título y el tamaño de la ventana. A continuación, creamos los distintos elementos de la ventana, como el selector de archivos, el cuadro desplegable y el botón de conversión:
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.file_picker = wx.FilePickerCtrl(panel, style=wx.FLP_OPEN)
vbox.Add(self.file_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
self.sheet_picker = wx.ComboBox(panel)
vbox.Add(self.sheet_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
self.output_picker = wx.FilePickerCtrl(panel, style=wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT)
vbox.Add(self.output_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
convert_btn = wx.Button(panel, label='Convert')
vbox.Add(convert_btn, proportion=0, flag=wx.ALIGN_CENTER | wx.ALL, border=10)
panel.SetSizer(vbox)
Usamos wx.FilePickerCtrl
para crear un selector de archivos para seleccionar archivos de Excel. Úselo para wx.ComboBox
crear un cuadro desplegable que muestre los nombres de las tablas en el archivo de Excel. Luego, usamos para wx.FilePickerCtrl
crear un selector de archivos para especificar la ruta de guardado del archivo PDF convertido. Finalmente, creamos un botón que desencadena la transición.
Implementar la operación de conversión.
A continuación, necesitamos implementar la lógica para la operación de transformación. Vincularemos los métodos de procesamiento correspondientes al evento del selector de archivos EVT_FILEPICKER_CHANGED
y al evento del botón de conversión .EVT_BUTTON
Primero, implementamos on_file_picker_changed
el método, que se llamará cuando el usuario seleccione un archivo de Excel. El método tomará la ruta al archivo seleccionado y utilizará pd.ExcelFile
los nombres de las tablas del archivo leído y los completará en el cuadro desplegable:
def on_file_picker_changed(self, event):
filepath = self.file_picker.GetPath()
sheets = self.get_excel_sheets(filepath)
self.sheet_picker.Clear()
self.sheet_picker.AppendItems(sheets)
if len(sheets) > 0:
self.sheet_picker.SetSelection(0)
Luego, implementamos on_convert_btn_click
el método, que se llamará cuando el usuario haga clic en el botón convertir. Este método obtendrá la ruta del archivo de Excel seleccionado, el nombre de la hoja seleccionada y la ruta del archivo de salida. Si se proporciona esta información, utilizará pd.read_excel
los datos leídos de Excel y llamará export_to_pdf
al método para exportar los datos como un archivo PDF:
def on_convert_btn_click(self, event):
excel_file = self.file_picker.GetPath()
sheet_name = self.sheet_picker.GetStringSelection()
output_file = self.output_picker.GetPath()
if excel_file and sheet_name and output_file:
excel_data = self.read_excel(excel_file, sheet_name)
if excel_data is not None:
self.export_to_pdf(excel_data, output_file)
wx.MessageBox('Conversion completed成功!')
def get_excel_sheets(self, file_path):
excel_file = pd.ExcelFile(file_path)
return excel_file.sheet_names
def read_excel(self, file_path, sheet_name):
try:
excel_data = pd.read_excel(file_path, sheet_name=sheet_name)
return excel_data
except Exception as e:
wx.MessageBox(f'Error reading Excel file: {
str(e)}', 'Error', wx.OK | wx.ICON_ERROR)
return None
def export_to_pdf(self, excel_data, output_file):
doc = fitz.open()
page = doc.new_page()
table = fitz.Table(page)
table.auto_table(excel_data.values.tolist(), excel_data.columns.tolist())
table.draw_on_page(page, (20, 20))
doc.save(output_file)
doc.close()
En el código anterior, get_excel_sheets
el método obtiene el nombre de la tabla en el archivo de Excel, read_excel
el método lee los datos de la tabla especificada y export_to_pdf
exporta los datos a un archivo PDF. Usamos la biblioteca PyMuPDF para crear un nuevo documento PDF, luego creamos una nueva página, dibujamos una tabla en la página y llenamos la tabla con datos. Finalmente guardamos el documento PDF y lo cerramos.
ejecutar la aplicación
Finalmente, necesitamos crear una wx.App
instancia, crearla y mostrarla ExcelToPDFFrame
. Luego, la llamada app.MainLoop()
ingresa al bucle de eventos principal, esperando la interacción del usuario:
if __name__ == '__main__':
app = wx.App()
frame = ExcelToPDFFrame(None, 'Excel to PDF Converter')
frame.Show()
app.MainLoop()
Ahora, hemos completado esta sencilla herramienta GUI de Excel a PDF. Puede guardarlo como un script de Python y ejecutarlo. Cuando abra la interfaz GUI, seleccione el archivo de Excel que desea convertir, el nombre de la tabla y la ruta del archivo PDF de salida, y luego haga clic en el botón de conversión para completar la operación de conversión.
todos los codigos
import wx
import pandas as pd
import fitz
class ExcelToPDFFrame(wx.Frame):
def __init__(self, parent, title):
super(ExcelToPDFFrame, self).__init__(parent, title=title, size=(400, 200))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.file_picker = wx.FilePickerCtrl(panel, style=wx.FLP_OPEN)
vbox.Add(self.file_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
self.sheet_picker = wx.ComboBox(panel)
vbox.Add(self.sheet_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
self.output_picker = wx.FilePickerCtrl(panel, style=wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT)
vbox.Add(self.output_picker, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
convert_btn = wx.Button(panel, label='Convert')
vbox.Add(convert_btn, proportion=0, flag=wx.ALIGN_CENTER | wx.ALL, border=10)
panel.SetSizer(vbox)
self.file_picker.Bind(wx.EVT_FILEPICKER_CHANGED, self.on_file_picker_changed)
convert_btn.Bind(wx.EVT_BUTTON, self.on_convert_btn_click)
def on_file_picker_changed(self, event):
filepath = self.file_picker.GetPath()
sheets = self.get_excel_sheets(filepath)
self.sheet_picker.Clear()
self.sheet_picker.AppendItems(sheets)
if len(sheets) > 0:
self.sheet_picker.SetSelection(0)
def on_convert_btn_click(self, event):
excel_file = self.file_picker.GetPath()
sheet_name = self.sheet_picker.GetStringSelection()
output_file = self.output_picker.GetPath()
if excel_file and sheet_name and output_file:
excel_data = self.read_excel(excel_file, sheet_name)
if excel_data is not None:
self.export_to_pdf(excel_data, output_file)
wx.MessageBox('Conversion completed successfully!', 'Success')
else:
wx.MessageBox('Failed to read Excel data. Please check the file and sheet name.', 'Error')
else:
wx.MessageBox('Please select an Excel file, sheet, and specify an output file path.', 'Error')
def get_excel_sheets(self, file_path):
sheets = []
try:
excel_data = pd.ExcelFile(file_path)
sheets = excel_data.sheet_names
except Exception as e:
print(str(e))
return sheets
def read_excel(self, file_path, sheet_name):
excel_data = None
try:
excel_data = pd.read_excel(file_path, sheet_name=sheet_name)
except Exception as e:
print(str(e))
return excel_data
def export_to_pdf(self, excel_data, output_file_path):
doc = fitz.open()
page = doc.new_page()
table_width = 400 # 设置表格宽度
table_height = excel_data.shape[0] * 25 + 25 # 设置表格高度
# 绘制表格边框
rect = fitz.Rect(50, 50, 50 + table_width, 50 + table_height)
page.draw_rect(rect)
# 设置表头样式
header_font = 'Helvetica'
# header_font_path = "/Noto_Sans_SC/static/NotoSansSC-Black.ttf" # 替换为您自己的字体文件路径
# header_font = fitz.Font(header_font_path)
# header_font = 'Noto Sans SC'
# header_font = 'SimSun'
# header_font = 'SimHei'
# header_font = 'Microsoft YaHei'
# header_font = 'LiSu'
# header_font = 'YouYuan'
# header_font = 'STSong'
# header_font = 'STHeiti'
# header_font = 'STKaiti'
# header_font = 'STFangsong'
# header_font = 'STZhongsong'
# header_font = 'STHupo'
header_fontsize = 12
header_color = (0, 0, 0)
header_bgcolor = (0.8, 0.8, 0.8)
# 绘制表头
for col_idx, column in enumerate(excel_data.columns):
header_rect = fitz.Rect(50 + col_idx * 100, 50, 50 + (col_idx + 1) * 100, 75)
page.draw_rect(header_rect, fill=header_bgcolor)
page.insert_textbox(header_rect, column, fontname=header_font, fontsize=header_fontsize, color=header_color, align=1)
# 设置单元格样式
# cell_font = "/Noto_Sans_SC/static/NotoSansSC-Black.ttf" # 替换为您自己的字体文件路径
# cell_font = fitz.Font(header_font_path)
# cell_font = 'Noto Sans SC'
cell_font = 'Helvetica'
# cell_font= 'SimSun'
# cell_font= 'SimHei'
# cell_font= 'Microsoft YaHei'
# cell_font= 'LiSu'
# cell_font= 'YouYuan'
# cell_font= 'STSong'
# cell_font= 'STHeiti'
# cell_font= 'STKaiti'
# cell_font= 'STFangsong'
# cell_font= 'STZhongsong'
# cell_font= 'STHupo'
cell_fontsize = 10
cell_color = (0, 0, 0)
# 绘制单元格内容
for row_idx, row in enumerate(excel_data.itertuples(index=False), start=1):
for col_idx, cell_value in enumerate(row, start=0):
cell_rect = fitz.Rect(50 + col_idx * 100, 75 + row_idx * 25, 50 + (col_idx + 1) * 100, 75 + (row_idx + 1) * 25)
# cell_rect = fitz.Rect(50 + col_idx * 100, 50 + row_idx * 75, 50 + (row_idx + 1) * 25)
page.insert_textbox(cell_rect, str(cell_value), fontname=cell_font, fontsize=cell_fontsize, color=cell_color, align=1)
doc.save(output_file_path)
doc.close()
app = wx.App()
frame = ExcelToPDFFrame(None, 'Excel to PDF Converter')
frame.Show()
app.MainLoop()
Resumen
En este blog, creamos una herramienta GUI para convertir Excel a PDF usando wxPython, pandas y la biblioteca PyMuPDF. A través de esta herramienta, podemos seleccionar fácilmente archivos, tablas y rutas de salida de Excel, y convertir datos de Excel en archivos PDF. Esta herramienta puede ayudarnos a ser más eficientes y convenientes al trabajar con datos de Excel, y también muestra cómo utilizar el lenguaje de programación Python y las bibliotecas relacionadas para lograr esta tarea. ¡Espero que este blog pueda ayudarte!