首先贴出四种方法适用范围比较:
注释:excel 2003 即xls文件有大小限制即65536行256列,所以不支持大文件。而excel 2007以上即xlsx文件的限制则为1048576行16384列
一、xlutils & xlrd & xlwt
最原始的莫过于两位老牌黄金搭档xlrd xlwt了,针对二者的封装有如下模块:
- xlutils:https://pypi.org/project/xlutils/
- xlrd:https://pypi.org/project/xlrd/
- xlwt:https://pypi.org/project/xlwt/
为什么把这三个一起说?
首先,xlutils封装了xlrd xlwt,所以在使用前,会先下载这两个依赖的模块。
其次,这两个模块主要用于处理xls文件,而对xlsx的文件处理很挫,甚至xlwt不支持…
但为何到现在依然在使用这些模块,因为他对xls文档处理的优势….
1、xlutils
官方文档:https://xlutils.readthedocs.io/en/latest/api.html
github项目:https://github.com/python-excel/xlutils
安装:(如果没安装xlrd、xlwt,会自动安装这2个模块)
pip install xlutils
使用:
import xlrd import xlwt import xlutils import xlutils.copy as copy rdbook = xlrd.open_workbook('first.xls') wtbook = copy.copy(rdbook) wtsheet = wtbook.get_sheet(0) type(wtsheet) wtsheet.write(0,0,'pcat.cc') wtbook.save('second.xls')
2、xlrd
xlrd is a library for reading data and formatting information from excel files, whether they are .xls or .xlsx files.
官方文档:https://xlrd.readthedocs.io/en/latest/api.html
github项目:https://github.com/python-excel/xlrd
安装:pip install xlrd
使用:只能读.xls、.xlsx文件(xlrd0.8.0+版本支持读取xlsx文件)
import xlrd book = xlrd.open_workbook("pcat.xls") print("the number of worksheets is {0}".format(book.nsheets)) print("worksheet name(s): {0}".format(book.sheet_names())) sh = book.sheet_by_index(0) print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols)) print("cell b3 is {0}".format(sh.cell_value(rowx=2, colx=1))) for rx in range(sh.nrows): print(sh.row(rx))
3、xlwt
xlwt is a library for writing data and formatting information to older excel files (ie: .xls)
官方文档:https://xlwt.readthedocs.io/en/latest/api.html
github项目:https://github.com/python-excel/xlwt
安装:pip install xlwt
使用:用xlwt创建一个简单的.xls文件
import xlwt from datetime import datetime style0 = xlwt.easyxf('font: name times new roman, color-index red, bold on', num_format_str='#,##0.00') style1 = xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss') wb = xlwt.workbook() ws = wb.add_sheet('a test sheet') ws.write(0, 0, 1234.56, style0) ws.write(1, 0, datetime.now(), style1) ws.write(2, 0, 1) ws.write(2, 1, 1) ws.write(2, 2, xlwt.formula("a3+b3")) wb.save('example.xls')
二、pandas(推荐)
pandas
https://www.pypandas.cn/
pandas作为数据分析利器,在读写excel方面,依赖库xlrd和xlwt。
import pandas as pd #方法一:默认读取第一个表单 df=pd.read_excel('lemon.xlsx')#这个会直接默认读取到这个excel的第一个表单 data=df.head()#默认读取前5行的数据 print("获取到所有的值:\n{0}".format(data))#格式化输出 #方法二:通过指定表单名的方式来读取 df=pd.read_excel('lemon.xlsx',sheet_name='student')#可以通过sheet_name来指定读取的表单 data=df.head()#默认读取前5行的数据 print("获取到所有的值:\n{0}".format(data))#格式化输出 #方法三:通过表单索引来指定要访问的表单,0表示第一个表单 #也可以采用表单名和索引的双重方式来定位表单 #也可以同时定位多个表单,方式都罗列如下所示 df=pd.read_excel('lemon.xlsx',sheet_name=['python','student'])#可以通过表单名同时指定多个 # df=pd.read_excel('lemon.xlsx',sheet_name=0)#可以通过表单索引来指定读取的表单 # df=pd.read_excel('lemon.xlsx',sheet_name=['python',1])#可以混合的方式来指定 # df=pd.read_excel('lemon.xlsx',sheet_name=[1,2])#可以通过索引 同时指定多个 data=df.values#获取所有的数据,注意这里不能用head()方法哦~ print("获取到所有的值:\n{0}".format(data))#格式化输出
三、xlsxwriter
https://xlsxwriter.readthedocs.io/
xlsxwriter拥有丰富的特性,支持图片/表格/图表/筛选/格式/公式等,功能与openpyxl相似,优点是相比 openpyxl 还支持 vba 文件导入,迷你图等功能,缺点是不能打开/修改已有文件,意味着使用 xlsxwriter 需要从零开始。
注意:xlsxwriter不支持.xls格式。
代码示例:
import xlsxwriter # create a workbook and add a worksheet. workbook = xlsxwriter.workbook('expenses01.xlsx') worksheet = workbook.add_worksheet() # some data we want to write to the worksheet. expenses = (['rent', 1000], ['gas', 100],['food', 300], ['gym', 50],) # start from the first cell. rows and columns are zero indexed. row = 0 col = 0 # iterate over the data and write it out row by row. for item, cost in (expenses): worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) row += 1 # write a total using a formula. worksheet.write(row, 0, 'total') worksheet.write(row, 1, '=sum(b1:b4)') worksheet.write('a1', 'hello world') workbook.close()
四、openpyxl(推荐)
读写 excel 2010 xlsx/xlsm files.
最后要说说个人比较常用,也很方便的一个excel处理模块openpyxl….这个模块突出的优势在于,对excel单元格样式的设置方面特别详细。
注意:openpyxl不支持.xls格式。读写文件前记得多备注,有时候可能有bug。
官方文档:https://openpyxl.readthedocs.io/en/stable/
安装:pip install openpyxl
1、写一个工作簿
from openpyxl import workbook from openpyxl.utils import get_column_letter wb = workbook() dest_filename = 'empty_book.xlsx' ws1 = wb.active ws1.title = "range names" for row in range(1, 40): ws1.append(range(600)) ws2 = wb.create_sheet(title="pi") ws2['f5'] = 3.14 ws2['a1'] = 42 # data can be assigned directly to cells ws2.append([1, 2, 3])# rows can also be appended # python types will automatically be converted import datetime ws2['a2'] = datetime.datetime.now() ws3 = wb.create_sheet(title="data") for row in range(10, 20): for col in range(27, 54): _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col))) print(ws3['aa10'].value) wb.save(filename = dest_filename)
2、读取现有工作簿
from openpyxl import load_workbook wb = load_workbook(filename = 'empty_book.xlsx') sheet_ranges = wb['sheet1'] print(sheet_ranges['d18'].value)
3.、插入图像 (需要依赖pillow..)
from openpyxl import workbook from openpyxl.drawing.image import image wb = workbook() ws = wb.active ws['a1'] = 'you should see three logos below' img = image('logo.png') # create an image ws.add_image(img, 'a1') # add to worksheet and anchor next to cells wb.save('logo.xlsx')
4、使用样式
样式用于在屏幕上显示时更改数据的外观。它们还用于确定数字的格式。
样式可以应用于以下方面:
- 字体设置字体大小,颜色,下划线等
- 填充以设置图案或颜色渐变
- 边框设置单元格上的边框
- 单元格排列
- 保护
以下是默认值:
from openpyxl.styles import patternfill, border, side, alignment, protection, font font = font(name='calibri',size=11,bold=false, italic=false,vertalign=none,underline='none',strike=false, color='ff000000') fill = patternfill(fill_type=none, start_color='ffffffff', end_color='ff000000') border = border(left=side(border_style=none,color='ff000000'), right=side(border_style=none,color='ff000000'), top=side(border_style=none, color='ff000000'), bottom=side(border_style=none, color='ff000000'), diagonal=side(border_style=none, color='ff000000'), diagonal_direction=0, outline=side(border_style=none,color='ff000000'), vertical=side(border_style=none,color='ff000000'), horizontal=side(border_style=none,color='ff000000') ) alignment=alignment(horizontal='general',vertical='bottom', text_rotation=0, wrap_text=false, shrink_to_fit=false, indent=0) number_format = 'general' protection = protection(locked=true, hidden=false)
到此这篇关于python使用openpyxl模块处理excel文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。