使用Python操作Excel(.xls)文件
1.xlrd读操作
wb = xlrd.open_workbook('fifles/data1.xls')
names = wb.sheet_names()
all_sheet = wb.sheets()
wb.sheet_by_name('')
wb.sheet_by_index()
m_r = sheet1.nrows
m_c = sheet1.ncols
sheet1.row_values(4)
sheet1.row_values(4, 1, 2)
sheet1.cell(1, 0)
print(sheet1.cell(1, 0).value)
sheet1.row(0)
sheet1.col(1)
2.xlwt写操作
import xlwt
wb = xlwt.Workbook()
student_sheet1 = wb.add_sheet('students1', cell_overwrite_ok=True)
student_sheet1.write(1, 1, '名字')
sty1 = xlwt.XFStyle()
font1 = xlwt.Font()
font1.name = '黑体'
font1.height = 20 * 20
font1.colour_index = 10
sty1.font = font1
boder1 = xlwt.Borders()
boder1.bottom = 10
boder1.bottom_colour = 12
sty1.borders = boder1
a1 = xlwt.Alignment()
a1.vert = xlwt.Alignment.VERT_CENTER
sty1.alignment = a1
p1 = xlwt.Pattern()
p1.pattern = xlwt.Pattern.SOLID_PATTERN
p1.pattern_fore_colour = 13
sty1.pattern = p1
student_sheet1.write_merge(1, 2, 3, 4, "hello")
student_sheet1.col(2).width = 30 * 256
student_sheet1.row(2).height_mismatch = True
student_sheet1.col(2).width = 30 * 60
student_sheet1.write(1, 1, '名字', style=sty1)
wb.save('fifles/students.xls')
3.utils修改操作
# 修改操作 utills
# 利用utills工具修改已经存在的xls文件
# xlrd只能读通过xlrd打开的Excel文件
# xlwt只能创建新的Excel文件无法获取已经存在的Excel文件
import xlrd, xlwt
from xlutils.copy import copy
# 1使用xlrd打开一个已经存在的只读的工作簿对象
wd = xlrd.open_workbook('fifles/data1.xls')
# 2.将只读的工作簿转换成可写的工作簿
wb1 = copy(wb)
sheet1 = wb1.add_sheet('')
wb1.save('fifles/data1.xls')