基於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 code
-
xml2excel.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 <memo>
#
#使用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 返回的字串類型為: <class 'PyQt4.QtCore.QString'>
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】