Python对Excel的读写主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter几种。
1.xlrd主要是用来读取excel文件
import xlrd
workbook = xlrd.open_workbook(u’有趣装逼每日数据及趋势.xls’)
sheet_names= workbook.sheet_names()
for sheet_name in sheet_names:
sheet2 = workbook.sheet_by_name(sheet_name)
print sheet_name rows = sheet2.row_values(3) # 获取第四行内容
cols = sheet2.col_values(1) # 获取第二列内容
print rows
print cols

2.xlwt主要是用来写excel文件
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet(‘sheet 1’)
sheet.write(0,1,’test text’)#第0行第一列写入内容
wbk.save(‘test.xls’)

3.xlutils结合xlrd可以达到修改excel文件目的
import xlrd
from xlutils.copy import copy
workbook = xlrd.open_workbook(u’有趣装逼每日数据及趋势.xls’)
workbooknew = copy(workbook)
ws = workbooknew.get_sheet(0)
ws.write(3, 0, ‘changed!’)
workbooknew.save(u’有趣装逼每日数据及趋势copy.xls’)

4.openpyxl可以对excel文件进行读写操作
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter

workbook = load_workbook(u”新歌检索失败1477881109469.xlsx”)
sheetnames =workbook
.getsheet_names() #获得表单名字
print sheetnames
sheet = workbook
.getsheet_by_name(sheetnames[0])
print sheet.cell(row=3,column=3).value
sheet[‘A1’] = ‘47’
workbook
.save(u”新歌检索失败1477881109469_new.xlsx”)
wb = Workbook()
ws = wb.active
ws[‘A1’] = 4
wb.save(“新歌检索失败.xlsx”)

5.xlsxwriter可以写excel文件并加上图表
import xlsxwriter

def get_chart(series):
chart = workbook.add_chart({‘type’: ‘line’})
for ses in series:
name = ses[“name”]
values = ses[“values”]
chart.add_series({
‘name’: name,
‘categories’: ‘A2:A10’,
‘values’:values
})
chart.set_size({‘width’: 700, ‘height’: 350})
return chart

if name == ‘main‘:
workbook = xlsxwriter.Workbook(u’H5应用中心关键数据及趋势.xlsx’)
worksheet = workbook.add_worksheet(u”每日PV,UV”)
headings = [‘日期’, ‘平均值’]
worksheet.write_row(‘A1’, headings)
index=0
for row in range(1,10):
for com in [0,1]:
worksheet.write(row,com,index)
index+=1
series = [{“name”:”平均值”,”values”:”B2:B10”}]
chart = get_chart(series)
chart.set_title ({‘name’: ‘每日页面分享数据’})
worksheet.insert_chart(‘H7’, chart)
workbook.close()

一、对excel的写操作实例:
将一个列表的数据写入excel, 第一行是标题,下面行数具体的数据
python操作Excel的几种方式 - 图1
python操作Excel的几种方式 - 图2
1 import xlwt 2 #只能写不能读 3 stus = [[‘姓名’, ‘年龄’, ‘性别’, ‘分数’], 4 [‘mary’, 20, ‘女’, 89.9], 5 [‘mary’, 20, ‘女’, 89.9], 6 [‘mary’, 20, ‘女’, 89.9], 7 [‘mary’, 20, ‘女’, 89.9] 8 ] 9 book = xlwt.Workbook()#新建一个excel 10 sheet = book.add_sheet(‘case1_sheet’)#添加一个sheet页 11 row = 0#控制行 12 for stu in stus: 13 col = 0#控制列 14 for s in stu:#再循环里面list的值,每一列 15 sheet.write(row,col,s) 16 col+=1 17 row+=1 18 book.save(‘stu_1.xls’)#保存到当前目录下
python操作Excel的几种方式 - 图3
python操作Excel的几种方式 - 图4
二、对excel 的读操作:
python操作Excel的几种方式 - 图5
python操作Excel的几种方式 - 图6
1 import xlrd 2 #只能读不能写 3 book = xlrd.open_workbook(‘stu.xls’)#打开一个excel 4 sheet = book.sheet_by_index(0)#根据顺序获取sheet 5 sheet2 = book.sheet_by_name(‘case1_sheet’)#根据sheet页名字获取sheet 6 print(sheet.cell(0,0).value)#指定行和列获取数据 7 print(sheet.cell(0,1).value) 8 print(sheet.cell(0,2).value) 9 print(sheet.cell(0,3).value) 10 print(sheet.ncols)#获取excel里面有多少列 11 print(sheet.nrows)#获取excel里面有多少行 12 print(sheet.get_rows())# 13 for i in sheet.get_rows(): 14 print(i)#获取每一行的数据 15 print(sheet.row_values(0))#获取第一行 16 for i in range(sheet.nrows):#0 1 2 3 4 5 17 print(sheet.row_values(i))#获取第几行的数据 18 19 print(sheet.col_values(1))#取第一列的数据 20 for i in range(sheet.ncols): 21 print(sheet.col_values(i))#获取第几列的数据
python操作Excel的几种方式 - 图7
python操作Excel的几种方式 - 图8
三、对excel的修改操作:
将excel中的某个值修改并重新保存
python操作Excel的几种方式 - 图9
python操作Excel的几种方式 - 图10
from xlutils.copy import copy import xlrd #xlutils:修改excel book1 = xlrd.open_workbook(‘stu.xls’) book2 = copy(book1)#拷贝一份原来的excel # print(dir(book2)) sheet = book2.get_sheet(0)#获取第几个sheet页,book2现在的是xlutils里的方法,不是xlrd的 sheet.write(1,3,0) sheet.write(1,0,’hello’) book2.save(‘stu.xls’)

############单元格常用设置##############################
1、设置超链接
#设置超链接

font = xlwt.Font() # Create Font
font.colour_index = 4 # 蓝色字体
font.underline=True
style = xlwt.XFStyle()
style.font = font
sheet.write(rowIndex,4,xlwt.Formula(‘HYPERLINK(“https://www.baidu.com";"baidu")'),style)
2、设置单元格背景色
#设置单元格背景色
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 5 #黄色
style = xlwt.XFStyle()
style.pattern = pattern
sheet.write(5, 5, ‘Cell Contents’, style)
‘’’ 颜色值
0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue,
5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon,
17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow ,
20 = Dark Magenta, 21 = Teal,
22 = Light Gray, 23 = Dark Gray
‘’’
3、设置粗字体
style = xlwt.easyxf(‘font: bold 1’)
sheet.write(5, 5, ‘Cell Contents’, style)
4、设置字体颜色
style = xlwt.easyxf(‘font: bold 0, color red;’)#红色字体
sheet.write(5, 5, ‘Cell Contents’, style)
5、设置列宽带
sheet.col(1).width = 3333 # 3333 = 1” (one inch)
6、设置日期格式
style = xlwt.XFStyle()
style.num_format_str = ‘YYYY/MM/DD h:mm:ss’
sheet.write(5, 5, datetime.datetime.now(), style)
python操作Excel的几种方式 - 图11
#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
7、合并行和列
sheet.write_merge(0, 0, 0, 3, ‘First Merge’)
sheet.write_merge(2, 4, 0, 3, ‘Second Merge’)
python操作Excel的几种方式 - 图12
8、给单元格增加边框
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED
# May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, #MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED,
#SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
python操作Excel的几种方式 - 图13
9、设置单元格中内容中位置,居中,局左右等
alignment = xlwt.Alignment() # Create Alignment
# May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT,
#HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.horz = xlwt.Alignment.HORZ_CENTER #水平居中
# May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER #垂直居中
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
sheet.write(5, 5, ‘Cell Contents’, style)