Top.Mail.Ru
Ответы

Код на python 3.10.6

Я пытаюсь сделать конвертор из xlsx в json
вот код

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
 import tkinter as tk 
from tkinter import filedialog, messagebox 
import pandas as pd 
import json 
 
def excel_to_json(file_path): 
    # Читаем Excel файл 
    df = pd.read_excel(file_path, header=None) 
     
    scenarios = [] 
    current_scenario = None 
     
    for _, row in df.iterrows(): 
        # Ищем ячейку с "Название" (игнорируя регистр) 
        title_cell = row[row.astype(str).str.contains('Название', na=False, case=False)].first_valid_index() 
         
        if title_cell is not None: 
            # Если нашли "Название", начинаем новый сценарий 
            if current_scenario: 
                scenarios.append(current_scenario) 
            current_scenario = {"name": str(row.get(title_cell + 1, "")), "questions": []} 
        elif current_scenario is not None: 
            # Ищем ячейки с "Вопрос", "Варианты ответов" и "Ответ" 
            question_cell = row[row.astype(str).str.contains('Вопрос', na=False, case=False)].first_valid_index() 
            options_cell = row[row.astype(str).str.contains('Вариант ответв', na=False, case=False)].first_valid_index() 
            answer_cell = row[row.astype(str).str.contains('Ответ', na=False, case=False)].first_valid_index() 
             
            if question_cell is not None: 
                question = str(row.get(question_cell + 1, "")) 
                options = [str(cell) for cell in row.iloc[options_cell + 1 : options_cell + 7] if pd.notna(cell)] if options_cell is not None else [] 
                answer = str(row.get(answer_cell + 1, "")) if answer_cell is not None else "" 
                 
                current_scenario["questions"].append({ 
                    "question": question, 
                    "options": options, 
                    "answer": answer 
                }) 
    # Добавляем последний сценарий 
    if current_scenario: 
        scenarios.append(current_scenario) 
     
    return json.dumps(scenarios, ensure_ascii=False, indent=2) 
class ExcelToJsonGUI: 
    def __init__(self, master): 
        self.master = master 
        master.title("Excel to JSON Converter") 
        master.geometry("400x200") 
        master.configure(bg="#e8f5e9")  # Светло-зеленый фон 
        self.label = tk.Label(master, text="Выберите Excel файл:", bg="#e8f5e9", fg="#1b5e20") 
        self.label.pack(pady=10) 
 
        self.select_button = tk.Button(master, text="Выбрать файл", command=self.select_file, bg="#4caf50", fg="white") 
        self.select_button.pack(pady=10) 
 
        self.convert_button = tk.Button(master, text="Конвертировать", command=self.convert_file, bg="#2e7d32", fg="white") 
        self.convert_button.pack(pady=10) 
 
        self.file_path = None 
 
    def select_file(self): 
        self.file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx;*.xls")]) 
        if self.file_path: 
            self.label.config(text=f"Выбранный файл: {self.file_path.split('/')[-1]}") 
 
    def convert_file(self): 
        if not self.file_path: 
            messagebox.showerror("Ошибка", "Пожалуйста, выберите файл") 
            return 
        try: 
            json_output = excel_to_json(self.file_path) 
            with open('scenario.json', 'w', encoding='utf-8') as f: 
                f.write(json_output) 
            messagebox.showinfo("Успех", "Файл успешно конвертирован и сохранен как scenario.json") 
        except Exception as e: 
            messagebox.showerror("Ошибка", f"Произошла ошибка при конвертации: {str(e)}") 
if __name__ == "__main__": 
    root = tk.Tk() 
    gui = ExcelToJsonGUI(root) 
    root.mainloop()  
По дате
По Рейтингу
Аватар пользователя
Новичок
9мес

а что не так? в коде ошибка или что?

Аватар пользователя
Профи
9мес

о спс