python办公自动化——excel

引言:python作为拥有丰富三方库的语言,办公自动化方面表现也很优异
开发工具:pycharm;excel; cmd

读写excel

此处通过python三方库:xlrd; xlwt
安装三方库,cmd输入pip install 三方库名:pip install xlrd

读excel

import xlrd

xlsx = xlrd.open_workbook('F:/k/test/test.xlsx')
table = xlsx.sheet_by_index(0)
#table = xlsx.sheet_by_name("sheet1") 读取表格的另一种方式
print(table.cell_value(1,2))
#print(table.cell(1,2).value)  另一种读取单元格的表达方式
#print(table.row(1)[2].value)   另一种读取单元格值得表达方式下

写excel

简单写excel

import xlwt

new_workbook = xlwt.Workbook()
worksheet = new_workbook.add_sheet('table001')
worksheet.write(0,0,"hola")
new_workbook.save('f:/k/test/demo.xlsx')

套用excel模板

使用模板excel进行新的excel内容填充

from xlutils.copy import copy
import xlrd
import xlwt

temp_excel = xlrd.open_workbook('f:/k/test/templateForExcel.xls', formatting_info=True)
temp_sheet = temp_excel.sheet_by_index(0)

new_excel = copy(temp_excel)
new_sheet = new_excel.get_sheet(0)
new_sheet.write(1,1, "考取PMP")
new_sheet.write(2, 1, "驾照延期")
new_sheet.write(3, 1, "多运动")
new_sheet.write(4, 1, "迎娶白富美!!")
new_excel.save("f:/k/test/toDoList.xls")

这样生成的excel中表格是没有样式的,可以自己添加样式

from xlutils.copy import copy
import xlrd
import xlwt

temp_excel = xlrd.open_workbook('f:/k/test/templateForExcel.xls', formatting_info=True)
temp_sheet = temp_excel.sheet_by_index(0)

new_excel = copy(temp_excel)
new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()
font.name = '微软雅黑' #设置字体
font.blod = True #是否加粗
font.height = 360 #字体大小:目标值*20
style.font = font

borders = xlwt.Borders()    #设置表格边框
borders.top = xlwt.Borders.THIN #设置线的格式
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders

alignment = xlwt.Alignment() #表格内字体对齐方式
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style.aligment = alignment


new_sheet.write(1,1, "考取PMP", style)
new_sheet.write(2, 1, "驾照延期", style)
new_sheet.write(3, 1, "多运动", style)
new_sheet.write(4, 1, "迎娶白富美!!", style)
new_excel.save("f:/k/test/toDoList.xls")

tips:
1、需要注意的是通过xl…的三方库尽量对.xls的excel进行操作,而不是.xlsx,对.xlsx的支持能力并不是很强
2、除了字典、数组等,直接用pandas进行数据操作也很方便

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值