引言: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进行数据操作也很方便
、