要想读取EXCEL中的数据,首先得下载xlrd包,地址:https://pypi.python.org/pypi/xlrd 安装方法:下载解压后,利用windows dos命令进入解压目录eg,cd E:\selenium--Pyton学习\Python软件\xlwt-1.0.0\xlwt-1.0.0,接下来输入命令:python setup.py install 即可,python中读取EXCEL数据看如下代码:
#coding=utf-8
import xlrd
my_file='E:\\baidu.xlsx' book=xlrd.open_workbook(my_file)
print book.nsheets
print book.sheets()
print book.sheet_names() #sheet = book.sheet_by_index(0) #通过索引顺序获取
sheet = book.sheet_by_name(u'Sheet1')#通过名称获取
print sheet.nrows#获取该xls表中所用行数
print sheet.ncols#获取该xls表中所用列数
print sheet.name#获取该sheet名字
print sheet.row(1)#获取第一行
print sheet.row_values(1)#获取第一行值列表
print sheet.col(1)#获取第一列
print sheet.col_values(1)#获取第一列值列表 cell=sheet.cell(2,1)#获取第2行第1列的值
cell_value = sheet.cell_value(2,1)#获取第2行第1列的值
#cell_value = sheet.cell(2,1).value#获取第2行第1列的值
print cell_value
以下为向EXCEL中写入数据:
xlwt 地址:http://pypi.python.org/pypi/xlwt
创建一个Excel文件并创建一个Sheet:
1
2
3
4
|
from xlwt import *
book = Workbook()
sheet = book.add_sheet( 'Sheet1' )
book.save( 'myExcel.xls' )
|
Workbook类可以有encoding和style_compression参数。
encoding,设置字符编码,style_compression,表示是否压缩。这样设置:w = Workbook(encoding='utf-8'),就可以在excel中输出中文了。默认是ascii。
向sheet写入内容:
1
|
sheet.write(r, c, label = "", style = Style.default_style)
|
简单写入:
1
|
sheet.write( 0 , 0 , label = 'Row 0, Column 0 Value' )
|
设置格式写入:
1
2
3
4
5
6
7
8
9
|
font = xlwt.Font() # 字体
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # 创建一个格式
style.font = font # 设置格式字体
sheet.write( 1 , 0 , label = 'Formatted value' , style) # Apply the Style to the Cell
book.save( 'myExcel.xls' )
|
写入日期:
1
2
3
|
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
sheet.write( 0 , 0 , datetime.datetime.now(), style)
|
写入公式:
1
2
3
4
|
sheet.write( 0 , 0 , 5 ) # Outputs 5
sheet.write( 0 , 1 , 2 ) # Outputs 2
sheet.write( 1 , 0 , xlwt.Formula( 'A1*B1' )) # 输出 "10" (A1[5] * A2[2])
sheet.write( 1 , 1 , xlwt.Formula( 'SUM(A1,B1)' )) # 输出 "7" (A1[5] + A2[2])
|
写入链接:
1
|
sheet.write( 0 , 0 , xlwt.Formula( 'HYPERLINK("http://www.google.com";"Google")' )) #输出 "Google"链接到http://www.google.com
|