作者:乔山办公网日期:
返回目录:excel表格制作
a = [[table.cell(i,ord('A')-ord('A')).value, table.cell(i,ord('B')-ord('A')).value] for i in range(1,nrows)]
相关知识如下:
Python操作excel要使用的库是:xlrd,xlwt;
操作步骤是:引用库文件,打开文件,获取表单,进行读写;
示例如下:
# -*- coding: utf-8 -*-
import xdrlib ,sys
import xlrd
def open_excel(file= 'file.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
#根据e68a847a686964616f361索引获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_index:表的索引
def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0):
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(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
#根据名称获取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
def main():
tables = excel_table_byindex()
for row in tables:
print row
tables = excel_table_byname()
for row in tables:
print row
if __name__=="__main__":
main()
这个过程有几个比较麻烦的问题,比如读取日期、读合并单元格内容。下面先看看基本的操作:
首先读一个excel文件,有两个sheet,测试用第二个sheet,sheet2内容如下:
python 对 excel基本的操作如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# -*- coding: utf-8 -*-
import xlrd
import xlwt
from datetime import date,datetime
def read_excel():
# 打开文件
workbook = xlrd.open_workbook(r'F:\demo.xlsx')
# 获取所有sheet
print workbook.sheet_names() # [u'sheet1', u'sheet2']
sheet2_name = workbook.sheet_names()[1]
# 根据sheet索引e799bee5baa6e79fa5e98193e59b9ee7ad94333或者名称获取sheet内容
sheet2 = workbook.sheet_by_index(1) # sheet索引从0开始
sheet2 = workbook.sheet_by_name('sheet2')
# sheet的名称,行数,列数
print sheet2.name,sheet2.nrows,sheet2.ncols
# 获取整行和整列的值(数组)
rows = sheet2.row_values(3) # 获取第四行内容
cols = sheet2.col_values(2) # 获取第三列内容
给你个例子吧。这个用起来,只要e68a84e799bee5baa6333学一个例子就可以会。
import xlutils,xlrd,xlwt
import os,glob,re,traceback,sys,time
from xlrd import open_workbook
from xlutils.copy import copy
def read_from_xlsx(fn_xlsx):
lists = []
try:
wb = xlrd.open_workbook(fn_xlsx)
except:
print u'文件不存在,或者无法打开,请关闭EXCEL:',fn_xlsx
return None
sh = wb.sheet_by_index(0)
//.................
for rownum in range(sh.nrows):
cols = sh.row_values(rownum)
cols = [unicode(c).strip() for c in cols]
其中关键是row_values。
你也可以在官网上找到例子代码。