欢迎使用CSDN-markdown编辑器

来源:互联网 发布:js表单验证正则表达式 编辑:程序博客网 时间:2024/05/16 01:33

[python]把excel转成xml

#需要下载xlrd库

# -- coding: utf-8 --
import xdrlib ,sys
import xlrd
import codecs
from xml.dom import minidom, Node

def readConfig():
print(“Start to read config…..”)
config = open(configFile, “r”)
configStr = config.read()
config.close()
print(“config content: ” + configStr)
xlsFileArr = configStr.split(“,”)
return xlsFileArr

#读取xls
def readXls(xlsFile):
print(“Start to read xls…..”, xlsFile)
dataList = []
xlsData = xlrd.open_workbook(xlsFile)
for sheet in xlsData.sheets():
# print(‘Sheet:’,sheet.name)
for row in range(sheet.nrows):
values = []
for col in range(sheet.ncols):
value = sheet.cell(row, col).value
values.append(value)
else :
#拿到单元格里超链接的值
link = sheet.hyperlink_map.get((row, 0))
if row == 0 :
values.append(linkText)
else :
values.append(link.url_or_path)
# print(link.url_or_path)
dataList.append(values)
return dataList

#保存为xml
def writeXml(xmlFile, dataList):
print(“Start to write xml……..”)

doc = minidom.Document()doc.appendChild(doc.createComment("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""))  #创建一个标签debugList = doc.createElement('deugList')   doc.appendChild(debugList)   valuesIndex = 0;for values in dataList:      valuesIndex = valuesIndex + 1    if valuesIndex == 1 :        continue    debugItem = doc.createElement('debug')     debugList.appendChild(debugItem)      valueIndex = 0;    for value in values:        itemTemp = doc.createElement(dataList[0][valueIndex])        debugItem.appendChild(itemTemp)          #对标签填充内容        itemTemp.appendChild(doc.createTextNode(value))        valueIndex = valueIndex + 1else :    f = codecs.open(xmlFile, encoding='utf-8', mode='w')      doc.writexml(f, "  ", "  ", "\n")    f.close() 

#主函数
def main():

xlsFileArr = readConfig()for xlsFile in xlsFileArr:    dataList = readXls(xlsFile)    xmlFile = xlsFile.split(".")[0]    writeXml(xmlFile + ".xml", dataList)

configFile = ‘config.txt’
linkText = “link”
main()

0 0