现在的位置: 首页 > 综合 > 正文

Python 将excel部分内容导入到XML文件

2014年08月13日 ⁄ 综合 ⁄ 共 3427字 ⁄ 字号 评论关闭

Python 将excel部分内容导入到XML文件

1. 参考文件链接:

http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html

http://www.2cto.com/kf/201205/133709.html

首先介绍下xlrd模块
准备工作. 安装xlrd模块
   到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。
进入命令行,在xlrd文件存放的文件夹下输入“Python setup.exe”进行模块安装。

一、Excel文件操作

1. 导入模块

   import xdrlib,sys,xlrd

2. 打开Excel文件获取数据

    data = xlrd.open_workbook('excelFile.xls')  #可以带上路径

3. 使用中需要的函数    获取一个Sheet

    table = data.sheets()[0]	#通过索引顺序获取
    table = data.sheet_by_name(u"Sheet1")	#通过名称获取
    table = data.sheet_by_index(0)	#通过索引获取


获取整行和整列的值(数组)

    table.row_values(i)
    table.col_values(i)


获取行数和列数

    nrows = table.nrows
    ncols = table.ncols


循环行列表数据

    for i in range(nrows):
        print table.row_values(i)


单元格

    cell_A1 = table.cell(0,0).value
    cell_A4 = table.cell(3,2).value


使用行列索引

    cell_A1 = table.row(0)[0].value
    cell_A2 = table.row(1)[0].value


简单的写入

    row = 0
    col = 0
	
    #类型 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error
    ctype = 1 value = "单元格的值"	
    xf = 0 #扩展的格式化
    table.put_cell(row,col,ctype,value,xf)
    table.cell(0,0)	#单元格的值
    talbe.cell(0,0).value	#单元格的值


二、写XML文件
1. 引入模块

    from xml.dom import minidom, Node 

2. 函数介绍

    创建文件
    doc = minidom.Document()
	
    加入注释
    doc.appendChild(doc.createComment("Simple xml document__chapter 8")) 
	
    创建属性
    book = doc.createElement('book')
    doc.appendChild(book)
	
    创建嵌套属性并填入值
    title = doc.createElement('title') 
    title.appendChild(doc.createTextNode("sample xml thing")) 
    book.appendChild(title)


结果显示
<?xml version="1.0" ?>
<book>
<title>
sample xml thing
</title>
</book>

附上我的源代码:

# -*- coding: utf-8 -*- 
import xdrlib,sys
import xlrd
import codecs
from xml.dom import minidom, Node
def open_excel(file='file.xls'):
 try:
  data=xlrd.open_workbook(file)
  return data;
 except Exception,e:
  print str(e)
#根据索引获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的索引 
#by_index:表的索引
def excel_table_byindex(file='D:\\fhuang6\My Documents\ECUProg\QingLing\Handbook.xls',colnameindex=0,by_index=1):
 data=open_excel(file)
 table=data.sheets()[by_index]
 nrows=table.nrows
 ncols=table.ncols
 colnames=table.row_values(colnameindex)
 list=[]
 for rownum in range(2,nrows):
  row=table.row_values(rownum)
  if row:
   element = []   
   for i in range(3,5):
    element.append(row[i])
   list.append(element)   
 return list
#根据名称获取Excel表格中的数据   参数:file:Excel文件路径 colnameindex:表头列名所在行的索引,by_name:Sheet1名称
#def excel_table_byname(file= 'file.xls',colnameindex=0,by_name=u'Sheet1'):        
# data = open_excel(file)
# table = data.sheet_by_name(by_name)
# nrows = table.nrows #行数 
# colnames =  table.row_values(colnameindex) #某一行数据 
# list =[]
# for rownum in range(1,nrows):
#  row = table.row_values(rownum)
#  if row:
#   app = {}
#   for i in range(len(colnames)):
#    app[colnames[i]] = row[i]
#   list.append(app)
# return list
#创建XML文件用于存放导出的数据
def write_xml(list):
 doc = minidom.Document()
 doc.appendChild(doc.createComment("strtDTC xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""))
 
 #generate the DTC 
 dtc = doc.createElement('_DTC') 
 doc.appendChild(dtc) 
 
 for Element in list:
  #the start_DTC
  startDTC = doc.createElement('_strtDTC') 
  dtc.appendChild(startDTC) 
 
  #the DTCShortName 
  DTCShortName = doc.createElement("DTCShortName") 
  startDTC.appendChild(DTCShortName)
  
  DTCCode = doc.createElement('DTCCode')
  startDTC.appendChild(DTCCode) 
  DTCCode.appendChild(doc.createTextNode(str(int(Element[1][1:],16))))
  
  Description = doc.createElement('Description') 
  startDTC.appendChild(Description) 
  Description.appendChild(doc.createTextNode(Element[0]))
 f = codecs.open('D:\Practice\RWExcel\Handbook.xml', encoding='utf8', mode='w')
 doc.writexml(f, "  ", "  ", "\n")
 f.close()  
 #print doc.toprettyxml() 

def main():
 tables = excel_table_byindex()
 write_xml(tables)
 #for row in tables:
 # print row

 #tables = excel_table_byname()
 #for row in tables:
 # print row
   
if __name__=="__main__":
 main()

【上篇】
【下篇】

抱歉!评论已关闭.