当前位置: 首页 > 后端技术 > Python

下面说说python办公自动化中的Excel(下)

时间:2023-03-26 01:44:14 Python

作者:新干果来源:AirPython前面说过,python处理Excel文件最常见的方式有两种,分别是:xlrd/xlwt、openpyxl。其中xlrd/xlwt的组合,xlrd可以负责读取数据,而xlwt负责写入数据,缺点是不支持xlsx。openpyxl也支持Excel文档的读写。缺点是不支持xls。本文将继续讲python操作Excel文档的其他几种方式。xlsxwriterxlsxwriter主要用于将数据和图表写入Excel文件,可以配置为以较小的内存快速写入数据。它的缺点是不能读取和修改已有的Excel文件;如果需要读取和修改Excel文件,只能配合其他依赖库使用,如:xlrd。首先安装xlsxwriter的依赖包:安装依赖包pip3installxlsxwriterxlsxwriter提供了创建工作簿对象的Workbook(filename)方法。使用工作簿对象的add_worksheet(sheet_name)函数在工作簿中创建一个Sheet。defcreate_workbook_and_worksheet(filename,worksheet_names):"""创建工作簿和Sheet:paramfilename:文件名:paramworksheet_names:工作表名称列表:return:"""wb=xlsxwriter.Workbook(filename)sheets=[]addsheetforworksheet_name在worksheet_names中:sheets.append(wb.add_worksheet(worksheet_name))returnwb,sheets然后,您可以将数据写入Sheet单元格。如果需要自定义单元格的样式,比如:字体大小、字体、颜色、背景、是否加粗等,可以使用工作簿对象的add_format()方法创建样式。defcreate_format_styles(wb,format_stuyles):"""创建样式,包括:字号、字体、颜色、背景、是否加粗等:paramwb::paramformat_stuyles::return:"""returnwb.add_format(format_stuyles)单元格字体样式self.title_style={'bold':True,'bg_color':'#B0C4DE','font_size':10,'font_name':'Microsoftyahei'}创建标题字体样式title_font_style=create_format_styles(self.wb,self.title_style)Sheet对象的write(...)函数用于向单元格写入数据,参数包括:行索引、列索引、值、字体样式等,需要注意的是xlsxwriter默认的行索引和列索引都是从0开始的,即:0代表第一行。写入数据时配置单元格样式的写法如下:defwrite_to_cell(sheet,row_index,column_index,value,format_styles=None):"""向单元格写入数据:paramrow_index:行索引,1:firstRow:paramcolumn_index:列索引,1:第一列:paramformat_styles字体样式:return:"""ifrow_index<1orcolumn_index<1:print('paraminputisincorrect,writefailed!')else:note:默认xlsxwriter的行索引和列索引从0开始。sheet.write(row_index-1,column_index-1,value,format_styles)将第一行数据写入工作表write_to_cell(self.current_sheet,1,1,"name"the同样支持在单元格中插入图片,包括:本地图片和网络图片,使用的方法为:insert_image();参数包括:单元格行索引(索引从0开始),单元格列索引,图片文件,可选参数(图片位置,zoom,url超链接,image_data图片字节流等)。以插入一张网页图片为例举个例子。首先定义一个图片显示的可选参数,指定图片的缩放比例,url超链接。defcreate_image_options(x_offset=0,y_offset=0,x_scale=1,y_scale=1,url=None,tip=None,image_data=None,positioning=None):"""插入图片的参数配置包括:offset,Zoom比率,网络图像链接,超链接,悬停指示灯:paramx_offset::paramy_offset::paramx_scale::paramy_scale::paramurl::paramtip::paramimage_data::parampositioning::return:"""image_options={'x_offset':x_offset,'y_offset':y_offset,'x_scale':x_scale,'y_scale':y_scale,'url':url,'tip':tip,'image_data':image_data,'positioning':定位,}returnimage_optionsimage_options=create_image_options(x_scale=0.5,y_scale=0.5,url='https://www.jianshu.com/u/f3b...')接下来将网络图片转成字节流:fromioimportBytesIOimportssldefget_image_data_from_network(url):"""获取网络图片字节流:paramurl:图片地址:return:"""ssl._create_default_https_context=ssl._create_unverified_context获取网络图片字节流image_data=BytesIO(urlopen(url).read())returnimage_data最后在单元格中插入图片:definsert_network_image(sheet,row_index,column_index,url,filepath,image_options=None):"""插入网络图sheet:paramsheet::paramrow_index::paramcolumn_index::paramurl::paramfilepath::paramimage_options::return:"""ifrow_index<1orcolumn_index<1:return"参数输入错误,插入失败!"获取图像字节流image_data=get_image_data_from_network(url)ifimage_options:image_options['image_data']=image_dataprint(image_options)sheet.insert_image(row_index-1,column_index-1,filepath,image_options)insert_network_image(self.current1,sheet,1,url,'1.png',image_options4)set_column()方法可以设置列宽,类似openpyxl,有2种使用方式,分别是:字符串索引,列索引编号索引defset_column_width(sheet,index_start,index_end,width):"""设置列宽:paramsheet::paramindex_start:起始位置,从1开始:paramindex_end:结束位置:paramwidth:width:return:"""选择其中一个两种方法self.current_sheet.set_column('A:C',width)默认第一列sheet为0.set_column(index_start-1,index_end-1,width)设置列宽,设置从第一列到第三列:100set_column_width(self.current_sheet,1,3,100)使用set_row()方法进行行高,传入行索引和行高即可。defset_row_height(sheet,row_index,height):"""设置行高:paramsheet::paramrow_index:行索引,从1开始:paramheight::return:"""sheet.set_row(row_index-1,height)设置行高set_row_height(self.current_sheet,1,50)set_row_height(self.current_sheet,2,100)写入数据后,关闭工作簿,文件会自动保存到本地。defteardown(self):写入文件,并关闭文件self.wb.close()xlsxwriter也支持插入图表,如:柱状图、直方图、雷达图等。限于篇幅,这部分内容就不展开解释了。其他方式还有一种比较常见的方式是:xlwings。xlwings是一个开源免费的依赖库,支持对Excel文件的读写和修改。非常强大,还可以和Matplotlib、Numpy、Pandas无缝对接,支持读写Numpy、Pandas数据类型;同时xlwings可以直接调用Excel文件中的VBA程序。需要注意的是,xlwings依赖于MicrosoftExcel软件,所以建议使用WPS的用户直接使用openpyxl。此外,还有一种更强大的Excel操作方式,即:Pywin32。其中Pywin32相当于在Win下调用系统API来操作Excel文件。优点是:可以处理复杂图表的数据表;缺点也很明显,包括:速度慢,CPU占用率高,只支持Win系统。最后发现xlrd/xlwt、openpyxl、xlsxwriter基本可以满足大部分日常的Excel文档操作。