写一个带界面的Excel转xml的程序
时间: 2023-12-01 09:03:06 浏览: 116
好的,这里给出一个简单的Excel转xml的程序,使用Python的Tkinter库来实现界面。
```
import tkinter as tk
from tkinter import filedialog
import openpyxl
import xml.etree.ElementTree as ET
class ExcelToXmlConverter:
def __init__(self, file_path):
self.file_path = file_path
self.workbook = openpyxl.load_workbook(file_path)
self.sheet = self.workbook.active
def convert_to_xml(self):
root = ET.Element('data')
for row in self.sheet.iter_rows():
data = ET.SubElement(root, 'row')
for cell in row:
ET.SubElement(data, cell.column_letter).text = str(cell.value)
tree = ET.ElementTree(root)
tree.write('output.xml')
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_file_button = tk.Button(self)
self.select_file_button["text"] = "Select Excel file"
self.select_file_button["command"] = self.select_file
self.select_file_button.pack(side="top")
self.convert_button = tk.Button(self)
self.convert_button["text"] = "Convert to XML"
self.convert_button["command"] = self.convert_to_xml
self.convert_button.pack(side="top")
self.quit = tk.Button(self, text="Quit", fg="red", command=self.master.destroy)
self.quit.pack(side="bottom")
def select_file(self):
file_path = filedialog.askopenfilename()
self.converter = ExcelToXmlConverter(file_path)
def convert_to_xml(self):
self.converter.convert_to_xml()
tk.messagebox.showinfo("Conversion complete", "XML file saved as output.xml")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
这个程序使用openpyxl库载入Excel文件,并使用xml.etree.ElementTree库生成XML文件。用户可以点击“Select Excel file”按钮选择Excel文件,然后点击“Convert to XML”按钮将Excel文件转换成XML文件,转换完成后会弹出一个消息框提示用户。用户也可以点击“Quit”按钮退出程序。
阅读全文