聊聊python办公自动化之Excel

哪家医院白癜风能治愈 http://pf.39.net/bdfyy/bdfrczy/141114/4517310.html

作者:星安果

来源:AirPython

python办公自动化之Excel(上)文章中,我们聊到使用xlrd、xlwt、xlutils这一组合操作Excel的方法。本篇文章将继续聊另外一种方式,即:openpyxl。

不得不说,openpyxl更强大!它支持xlsx格式的表格文件,并且支持Numpy、Pandas等包,可用于绘制图表。

准备:首先,我们需要安装依赖包。

#安装依赖包pip3installopenpyxl

读取数据:使用openpyxl中的load_workbook(filepath)加载本地一个Excel文件,返回结果是一个工作簿对象。

importopenpyxl#加载本地的Excel文件wb=openpyxl.load_workbook(file_path)

利用工作簿对象,可以获取所有的Sheet名称及Sheet列表。

defget_all_sheet_names(wb):获取所有sheet的名称:paramwb::return:#sheet名称列表sheet_names=wb.sheetnamesreturnsheet_namesdefget_all_sheet(wb):获取所有的sheet:paramwb::return:#sheet名称列表sheet_names=get_all_sheet_names(wb)#所有sheetsheets=[]forsheet_nameinsheet_names:sheet=wb[sheet_name]sheets.append(sheet)returnsheets

工作簿对象提供了active属性,用于快速获取当前选择的Sheet。

defget_current_sheet(wb):获取当前选择的sheet,默认是最后一个sheet:paramwb::return:#当前选中的sheetcurrent_sheet=wb.activereturncurrent_sheet

另外,也可以通过Sheet名称去获取某一个特定的Sheet对象。

defget_sheet_by_name(wb,sheet_name):通过sheetname去查找某一个sheet:paramwb::paramsheet_name::return:sheet_names=get_all_sheet_names(wb)ifsheet_nameinsheet_names:result=wb[sheet_name]else:result=Nonereturnresult

使用sheet.max_row和sheet.max_column可以获取当前Sheet中的数据行数和列数。

defget_row_and_column_num(sheet):获取sheet的行数和列数:paramsheet::return:#行数row_count=sheet.max_row#列数column_count=sheet.max_columnreturnrow_count,column_count#行数和列数row_count,column_count=get_row_and_column_num(sheet)print(行数和列数分别为:,row_count,column_count)

openpyxl提供2种方式来定位一个单元格,分别是:

数字索引,从1开始数字索引:行数字索引、列数字索引比如:row_index=1,column_index=1行和列组成的字符串索引字符串索引:列由字母组成+行索引比如:A1对应第一行、第一列的单元格。并且,openpyxl.utils提供了方法,便于列索引在两者之间进行转换。

fromopenpyxl.utilsimportget_column_letter,column_index_from_stringdefcolumn_num_to_str(num):Excel索引列从数字转为字母:paramnum::return:returnget_column_letter(num)defcolumn_str_to_num(str):Excel索引列,从字母转为数字:paramstr::return:returncolumn_index_from_string(str)

单元格的获取,同样可以通过上面2种索引方式来获取。

defget_cell(sheet,row_index,column_index):获取单元格:paramsheet::paramrow_index::paramcolumn_index::return:#openpyxl索引都是从1开始计数,这与xlrd有所不同#获取某一个单元格(二选一)#比如:获取A1单元格的数据,即第一个行、第一列的数据#cell_one=sheet[A1]cell_one=sheet.cell(row=row_index,column=column_index)returncell_one

在日常处理Excel数据过程中,可能需要判断单元格数据类型,而openpyxl并没有提供现成的方法。这里,我们可以通过单元格对象的value属性拿到值,接着使用isinstance方法判断数据类型。

defget_cell_value_and_type(cell):获取某一个cell的内容及数据类型:paramcell::return:#单元格的值cell_value=cell.value#单元格的类型cell_type=get_cell_value_type(cell_value)returncell_value,cell_typedefget_cell_value_type(cell_value):获取数据类型:paramcell_value::return:#其中#0:空#1:数字#2:字符串#3:日期#4:其他ifnotcell_value:cell_type=0elifisinstance(cell_value,int)orisinstance(cell_value,float):cell_type=1elifisinstance(cell_value,str):cell_type=2elifisinstance(cell_value,datetime.datetime):cell_type=3else:cell_type=4returncell_type=

单独获取某一行[列]的数据,可以使用下面的方式:

defget_row_cells_by_index(sheet,row_index):通过行索引,获取某一行的单元格:paramrow_index::return:#注意:第一列从1开始row_cells=sheet[row_index]returnrow_cellsdefget_column_cells_by_index(sheet,column_index):通过列索引,获取某一列的单元格#数字转为字母column_index_str=column_num_to_str(column_index)#获取某一列的数据column_cells=sheet[column_index_str]returncolumn_cells

需要注意的是,获取某一行的数据需要传入数字索引;而对于列数据的获取,必须传入字符串索引。和Python列表范围取值类似,openpyxl同样支持使用:符号拿到某个范围内的数据行[列]

defget_rows_by_range(sheet,row_index_start,row_index_end):通过范围去选择行范围比如:选择第2行到第4行的所有数据,返回值为元组:paramsheet::paramrow_index_start::paramrow_index_end::return:rows_range=sheet[row_index_start:row_index_end]returnrows_rangedefget_columns_by_range(sheet,column_index_start,column_index_end):通过范围去选择列范围比如:选择第2列到第4列的所有数据,返回值为元组:paramsheet::paramcolumn_index_start::paramcolumn_index_end::return:columns_range=sheet[column_num_to_str(column_index_start):column_num_to_str(column_index_end)]returncolumns_range

写入数据

要写入数据到Excel表格。首先,使用openpyxl.Workbook()创建一个Excel工作簿对象。接着,使用工作簿对象的create_sheet()新建一个Sheet。

#创建一个Excel工作簿#注意:每次新建一个Excel文件,都会默认生成一个名称为的工作表Sheetwb=openpyxl.Workbook()#创建一个新的sheet,默认被插到尾部#new_sheet=wb.create_sheet(新的Sheet)#也可以通过第二个参数:index来指定插入的位置#比如:插入到开头new_sheet=wb.create_sheet(新的Sheet,0)

默认创建的Sheet被插入到最后一个位置,第2个参数可以指定Sheet插入的位置。

Sheet标签的背景色同样支持修改,使用sheet_properties.tabColor指定RGB颜色值。

比如,要设置某一个Sheet的背景色为红色,只需要先查询到对应的Sheet,然后指定颜色值为FF即可。

defset_sheet_bg_color(sheet,rgb_value):设置Sheet标签的颜色:paramrgb_value::return:#设置Sheet底部按钮的颜色(RRGGBB)sheet.sheet_properties.tabColor=rgb_value#设置Sheet的背景色(红色)set_sheet_bg_color(new_sheet,FF)

openpyxl支持行列数字索引、字符串索引以这2种方式写入数据到单元格中。

defwrite_value_to_cell_with_num(sheet,row_index,column_index,value):按行索引、列索引写入数据:paramshell::paramrow_index:行索引:paramcolumn_index:列索引:paramvalue::return:#二选一sheet.cell(row=row_index,column=column_index,value=value)#shell.cell(row=row_index,column=column_index).value=valuedefwrite_value_to_cell_with_index_str(sheet,index_str,value):按字母位置,写入数据到对应单元格:paramshell::paramindex_str:字母对应的单元格位置:paramvalue::return:sheet[index_str]=value

在单元格中插入图片也很简单,openpyxl提供的add_image()方法。参数有2个,分别是:图片对象、单元格字符串索引。为了便于使用,我们可以将列索引进行转换,然后封装成两个插入图片的方法。

fromopenpyxl.drawing.imageimportImagedefinsert_img_to_cell_with_num(sheet,image_path,row_index,column_index):往单元格中插入图片:paramsheet::paramimage_path::paramrow_index::paramcolumn_index::return:#通过行索引、列索引,获取到字母索引index_str=column_num_to_str(column_index)+str(row_index)insert_img_to_cell_with_str(sheet,image_path,index_str)definsert_img_to_cell_with_str(sheet,image_path,index_str):往单元格中插入图片:paramsheet::paramimage_path::paramindex_str::return:sheet.add_image((image_path),index_str)

最后,调用工作簿对象的save()方法,将数据真实写入到Excel文件中。

#注意:必须要写入,才能真实的保存到文件中wb.template=Falsewb.save(new.xlsx)

修改数据

修改数据包含:单元格数据的修改、单元格样式的修改。对于单元格数据的修改,只需要先读取工作簿对象,查询到要操作的Sheet对象,然后调用上面的方法修改单元格数据,最后调用save()函数保存覆盖即可。

defmodify_excel(self,file_path):修改本地Excel文件中数据:paramfile_path::return:#读取本地Excel文件wb=openpyxl.load_workbook(file_path)#读取某一个sheetsheet=wb[第一个Sheet]print(sheet)#直接修改某一个单元格的数据write_value_to_cell_with_num(sheet,1,1,姓名1)#保存并覆盖wb.save(file_path)

单元格样式包含:字体样式、单元格背景样式、边框样式、对齐方式等。以常见的字体样式、对齐方式为例。

首先,使用openpyxl中的Font类创建一个对象,指定字体名称、字体大小、是否加粗、是否斜体、颜色、下划线等。

fromopenpyxl.stylesimportFont#字体格式#指定字体类型、大小、是否加粗、颜色等font0=Font(name=Calibri,size=20,bold=False,italic=False,vertAlign=None,underline=none,strike=False,color=FF00FF00)

接着,构建一个Alignment对象,指定单元格的对齐方式。

fromopenpyxl.stylesimportFont,Alignment#单元格对齐方式alignment0=Alignment(horizontal=center,vertical=bottom,text_rotation=0,wrap_text=False,shrink_to_fit=False,indent=0)

最后,使用单元格对象的font/alignment属性,将字体样式和对齐方式设置进去即可。

#设置属性样式(字体、对齐方式)sheet[A1].font=font0sheet[A1].alignment=alignment0

6.进阶用法

接下来,聊聊几个常用的进阶用法:

1、获取可见及隐藏的Sheet

通过判断Sheet对象的sheet_state属性值,可以判断当前Sheet是显示还是隐藏。当值为visible时,代表Sheet是显示的。当值是hidden时,代表这个Sheet被隐藏了。

defget_all_visiable_sheets(wb):获取工作簿中所有可见的sheet:paramwb::return:return[sheetforsheetinget_all_sheet(wb)ifsheet.sheet_state==visible]defget_all_hidden_sheets(wb):获取工作簿中所有隐藏的sheet:paramwb::return:return[sheetforsheetinget_all_sheet(wb)ifsheet.sheet_state==hidden]

2、获取隐藏/显示的行索引列表、列索引列表

受限于篇幅,这里以获取所有显示/隐藏的行索引列表为例,遍历Sheet对象的row_dimensions属性值,通过判断行属性的hidden值,判断当前行是否隐藏或显示。

defget_all_rows_index(sheet,hidden_or_visiable):获取所有隐藏/显示的行:paramhidden_or_visiable:True:隐藏;False:显示:paramsheet::return:#遍历行#隐藏的索引hidden_indexs=[]#所有隐藏的行索引forrow_index,rowDimensioninsheet.row_dimensions.items():ifrowDimension.hidden:hidden_indexs.append(row_index)#所有显示的行索引visiable_indexs=[index+1forindexinrange(get_row_and_column_num(sheet)[0])ifindex+1notinhidden_indexs]#隐藏或者显示的行索引列表returnhidden_indexsifhidden_or_visiableelsevisiable_indexs、

3、获取单元格字体颜色及单元格背景颜色

单元格对象的font.color.rgb、fill.fgColor.rgb属性值分别代表字体颜色值、单元格背景颜色。

defget_cell_font_color(sheet,row_index,column_index):获取单元格字体的颜色:paramsheet::paramrow_index:行索引:paramcolumn_index:列索引:return:cell_color=sheet.cell(row_index,column_index).font.colorifcell_color:returnsheet.cell(row_index,column_index).font.color.rgbelse:#颜色不存在,可能单元格没有数据returnNonedefget_cell_bg_color(sheet,row_index,column_index):获取单元格背景的颜色:paramsheet::paramrow_index:行索引:paramcolumn_index:列索引:return:returnsheet.cell(row_index,column_index).fill.fgColor.rgb

最后

可以发现,openpyxl相比xlrd/xlwt,提供了大量实用的API,功能更强大,并且完美支持xlsx!



转载请注明地址:http://www.shiquanren.net/itcj/itcj/27140.html


  • 上一篇文章:
  • 下一篇文章: 没有了
  • 公司简介 广告合作 发布优势 服务条款 隐私保护 网站地图 版权声明