基于python的xml与ms excel的互转系统
test_ui.py(工具自动生成的,所以这个代码不需要讨论,贴出来完全为了本设计完整)
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'xml-excel2.ui'
#
# Created: Tue Dec 09 13:42:25 2008
# by: PyQt4 UI code generator 4.4.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(50, 250, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtGui.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(270, 250, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.textEdit = QtGui.QTextEdit(Form)
self.textEdit.setGeometry(QtCore.QRect(0, 70, 311, 21))
self.textEdit.setObjectName("textEdit")
self.textEdit_2 = QtGui.QTextEdit(Form)
self.textEdit_2.setGeometry(QtCore.QRect(0, 170, 311, 21))
self.textEdit_2.setObjectName("textEdit_2")
self.pushButton_3 = QtGui.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(320, 70, 75, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(10, 30, 81, 16))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(10, 140, 131, 20))
self.label_2.setObjectName("label_2")
self.label_3 = QtGui.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(240, 10, 141, 20))
self.label_3.setObjectName("label_3")
self.retranslateUi(Form)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), Form.close)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "xml-excel浜?杞????, None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Form", "杞????", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("Form", "???沐??, None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_3.setText(QtGui.QApplication.translate("Form", "娴?瑙?", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "璇疯????ヨ浆??㈡??锛?, None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Form", "璇疯????ヨ浆??㈢?????璺?寰?锛?", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Form", "version:0.1 浣?琚??锛???瑰??", None, QtGui.QApplication.UnicodeUTF8))
回复1:
Python codexml2excel.py
[code=Python]
# coding=utf-8
import sys
from PyQt4 import QtCore, QtGui
from test_ui import Ui_Form
from pyExcelerator import *
import xlrd
from xml.dom.minidom import *
#------------------------------------
#excel2xml(source_path,target_path)
#excel file translate to xml file
#source_path:excel文件源的路径
#target_path:xml目标文件的路径
#------------------------------------
def excel2xml(source_path,target_path):
book = xlrd.open_workbook(source_path)
sh = book.sheet_by_index(0)
#保存工作表的列的数量
sheet_ncol=sh.ncols
#保存工作表的行的数量
sheet_nrow=sh.nrows
# 写xml
# Create the minidom document
doc = Document()
# Create the base element
demo = doc.createElement("demo")
doc.appendChild(demo)
# Create the main element
#注意:标签不能有空格或特殊字符 比如‘#’ 否则浏览器不能解析xml
#默认标题都是英文,中文处理还存在问题
for x in range(sheet_nrow-1):
maincard = doc.createElement("list")
demo.appendChild(maincard)
for y in range(sheet_ncol):
#Create a element
paragraph1 = doc.createElement(sh.cell(0,y).value)
maincard.appendChild(paragraph1)
# Give the elemenet some text
ptext = doc.createTextNode(str(sh.cell(x+1,y).value))#节点必须是字符串,所以使用str()
paragraph1.appendChild(ptext)
try:
xmlfile=open(target_path,'w')
xmlfile.write(doc.toprettyxml())
xmlfile.close()
message_box_success()
except IOError:
message_box_exception()
def xml2excel(source_path,target_path):
'path参数应该是全名,包括.xml后缀'
'也支持OOo,即openoffice.org'
xmldoc = parse(source_path)
root = xmldoc.documentElement#here root is
#
#使用pyExcelerator模块
#
w = Workbook()#生成工作簿
ws = w.add_sheet('Hey, Dude')#加入一个工作表并命名
#------------------------------
#输出子标签名信息
#------------------------------
node = root.childNodes[1]#caution:父标签和子标签之间有空格或回车,空格和回车会被认为是父标签的一个子节点
#所以,在xml的源代码中 应该看父子间有无空格,正常人书写xml文件应该有空格或换行
j=0
if node.nodeType == node.ELEMENT_NODE:
for node in node.childNodes:
if node.nodeType == node.ELEMENT_NODE:
ws.write(0, j, node.nodeName)
j+=1
#----------------------------------
#输出xml文档中的所有内容信息
#----------------------------------
row=0
col=0
for node in root.childNodes:
if node.nodeType==node.ELEMENT_NODE:#这条判断语句是后来调试加上去的,因为空格也算子节点
col=0
row+=1
for x in node.childNodes:
if x.nodeType == x.TEXT_NODE :#子节点是空格或回车的情况
continue
else:
ws.write(row, col, x.firstChild.data)
col+=1
print row
try:
w.save(target_path)#保存
message_box_success()
except IOError:
message_box_exception()
def message_box_success():
'when the translate is success,you can invoke that'
message = QtGui.QMessageBox()
message.setWindowTitle('over')
message.setIcon(QtGui.QMessageBox.Information)
message.setText('create complete!')
message.exec_()
def message_box_exception():
'when raise ioexception ,you can invoke that'
message = QtGui.QMessageBox()
message.setWindowTitle('over')
message.setIcon(QtGui.QMessageBox.Information)
message.setText('the file of source or target is not exsit!')
message.exec_()
def message_box_format():
'when the format of source file is uncorrect'
message = QtGui.QMessageBox()
message.setWindowTitle('over')
message.setIcon(QtGui.QMessageBox.Information)
message.setText('the format of source file is uncorrect')
message.exec_()
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.pushButton_3,QtCore.SIGNAL("clicked()"), self.file_dialog)#pushButton_3:”浏览“按钮对象名 设置信号/槽函数
QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), self.file_translate)#pushButton:转换 按钮对象名 设置信号/槽函数
def file_dialog(self):
fd = QtGui.QFileDialog(self)
self.filename = fd.getOpenFileName()#得到打开的文件名 caution 返回的字符串类型为:
self.ui.textEdit.setText(self.filename)#textEdit为转换源文本框的对象名
if str(self.filename).endswith('xls'):
self.ui.textEdit_2.setText("c:\fang.xml")#设置默认的输出路径
if str(self.filename).endswith('xml'):
self.ui.textEdit_2.setText("c:\fang.xls")#设置默认的输出路径
def file_translate(self):
self.filename1=self.ui.textEdit_2.toPlainText()#获得textEdit_2的文本内容
print type(str(self.filename))
if str(self.filename).endswith('xls'):
excel2xml(self.filename,self.filename1)
elif str(self.filename).endswith('xml'):
xml2excel(str(self.filename),self.filename1)#caution str(self.filename)才是python里面的普通字符串类型
else:
message_box_format()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
我先自己来说几个缺点:
1,定义了多个功能相同的message_box_xxxx()函数,完全可以改写成为一个这个函数,弹出的提示信息通过参数传进
2,有些变量命名不够规范,以及注释也不太美观等
[/code]
回复2: 你这个系统中主要的工作就是读取xml文件,转换xml文件中的格式,然后再把转换后的结果写入execel文件,所以你可以把业务逻辑抽出来,具体的读取或写入xml文件的功能可以委托给XmlParser类,读取或写入execel文件的功能可以委托为ExecelParser类,而格式转换功能你可以用单独的函数或是类来实现。这样子分离应该便于后期的修改或是扩展吧。
个人的愚见,呵呵,也不知道是不是正确。
回复3: 继续等待
回复4: 呵呵别等了,除了我这种闲人会过来??嗦两句。别人都很忙的。
回复5: 长???
回复6: 有点意思
回复7: 帮顶
回复8: 独自等待
回复9: 来学习
回复10: 有点意思,不过意义不大
【Reprinted from 最后的骑士: http://bbs.palmjob.net/1008/090119094706640-1.htm】