Как сделать взаимодействие программы (python) с exel или word файлом?
Хочу реализовать программу, которая с помощью виджетов сможет взаимодействовать с эксэль или ворд файлом (например, написал текст в окне программы, он отобразился в какой-нибудь ячейке эксель и тд), а в конечном итоги по нажатию клавиши печатать этот файл. Возможно ли такое реализовать, если да, то какие библиотеки это позволят сделать? Я так понимаю, с tkinter или customtkinter не получится.
Ответы (1 шт):
Автор решения: Amgarak
→ Ссылка
Вот вам небольшой пример:
import openpyxl
from PyQt6.QtWidgets import QApplication, QTextEdit, QDialog, QPushButton, QVBoxLayout, QWidget, QFileDialog
from PyQt6.QtPrintSupport import QPrintDialog, QPrinter
def print_selected_text(editor, printer):
dialog = QPrintDialog(printer)
if editor.textCursor().hasSelection():
dialog.addEnabledOption(QPrintDialog.PrintDialogOption.PrintSelection)
if dialog.exec() == QDialog.DialogCode.Accepted:
editor.print(printer)
def save_to_excel(text):
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = text
wb.save("output.xlsx")
def choose_file_and_print(editor, printer):
file_path, _ = QFileDialog.getOpenFileName(None, None, None, "Excel Files (*.xlsx)")
if file_path:
wb = openpyxl.load_workbook(file_path)
ws = wb.active
text = ""
for row in ws.iter_rows(values_only=True):
text += '\t'.join(str(cell) for cell in row) + '\n'
editor.setPlainText(text)
print_selected_text(editor, printer)
if __name__ == '__main__':
app = QApplication([])
printer = QPrinter()
main_window = QWidget()
layout = QVBoxLayout(main_window)
editor = QTextEdit()
print_button = QPushButton("Напечатать текст с формы")
print_button.clicked.connect(lambda: print_selected_text(editor, printer))
save_button = QPushButton("Сохранить в Excel")
save_button.clicked.connect(lambda: save_to_excel(editor.toPlainText()))
choose_file_button = QPushButton("Выбрать exel файл для печати")
choose_file_button.clicked.connect(lambda: choose_file_and_print(editor, printer))
layout.addWidget(editor)
layout.addWidget(print_button)
layout.addWidget(save_button)
layout.addWidget(choose_file_button)
main_window.setLayout(layout)
main_window.show()
app.exec()
Интерфейс и печать через PyQt6, а работа с exel через openpyxl.
Разумеется это лишь демонстрационный пример и его нужно доработать.