Python使用openpyxl模块处理Excel文件


Posted in Python onJune 05, 2022

首先贴出四种方法适用范围比较:

注释:Excel 2003 即XLS文件有大小限制即65536行256列,所以不支持大文件。而Excel 2007以上即XLSX文件的限制则为1048576行16384列

一、xlutils & xlrd & xlwt

最原始的莫过于两位老牌黄金搭档xlrd 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文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。


Tags in this post...

Python 相关文章推荐
使用Python的Treq on Twisted来进行HTTP压力测试
Apr 16 Python
深入解析Python中函数的参数与作用域
Mar 20 Python
利用python微信库itchat实现微信自动回复功能
May 18 Python
Python面向对象之反射/自省机制实例分析
Aug 24 Python
python通过tcp发送xml报文的方法
Dec 28 Python
对django中foreignkey的简单使用详解
Jul 28 Python
解决Python计算矩阵乘向量,矩阵乘实数的一些小错误
Aug 26 Python
基于spring boot 日志(logback)报错的解决方式
Feb 20 Python
Python接口自动化判断元素原理解析
Feb 24 Python
浅谈keras.callbacks设置模型保存策略
Jun 18 Python
Python之字典对象的几种创建方法
Sep 30 Python
健身房被搭讪?用python写了个小米计时器助人为乐
Jun 08 Python
Python中requests库的用法详解
Jun 05 #Python
Python加密与解密模块hashlib与hmac
Jun 05 #Python
Python日志模块logging用法
Jun 05 #Python
Python使用Beautiful Soup(BS4)库解析HTML和XML
Jun 05 #Python
Python四款GUI图形界面库介绍
Python序列化模块JSON与Pickle
Jun 05 #Python
python 判断字符串当中是否包含字符(str.contain)
You might like
怎样辨别一杯好咖啡
2021/03/03 新手入门
PHP Array交叉表实现代码
2010/08/05 PHP
php中serialize序列化与json性能测试的示例分析
2013/04/27 PHP
smarty自定义函数htmlcheckboxes用法实例
2015/01/22 PHP
php中注册器模式类用法实例分析
2015/11/03 PHP
PHP实现求两个字符串最长公共子串的方法示例
2017/11/17 PHP
javascript 函数调用的对象和方法
2010/07/01 Javascript
IE的fireEvent方法概述及应用
2013/02/22 Javascript
单击复制文字兼容各浏览器的完美解决方案
2013/07/04 Javascript
jQuery :first选择器使用介绍
2013/08/09 Javascript
利用jQuery实现可以编辑的表格
2014/05/26 Javascript
Javascript的严格模式strict mode详细介绍
2014/06/06 Javascript
jQuery插件imgPreviewQs实现上传图片预览
2016/01/15 Javascript
js+html5实现的自由落体运动效果代码
2016/01/28 Javascript
详解nodejs中的process进程
2017/03/19 NodeJs
Angular2平滑升级到Angular4的步骤详解
2017/03/29 Javascript
Three.js实现浏览器变动时进行自适应的方法
2017/09/26 Javascript
ES6 Promise对象概念及用法实例详解
2019/10/15 Javascript
vue 根据选择的月份动态展示日期对应的星期几
2021/02/06 Vue.js
树莓派中python获取GY-85九轴模块信息示例
2013/12/05 Python
python批量制作雷达图的实现方法
2016/07/26 Python
python一键升级所有pip package的方法
2017/01/16 Python
python 使用get_argument获取url query参数
2017/04/28 Python
Django框架使用内置方法实现登录功能详解
2019/06/12 Python
基于python实现从尾到头打印链表
2019/11/02 Python
pandas使用之宽表变窄表的实现
2020/04/12 Python
opencv+python实现鼠标点击图像,输出该点的RGB和HSV值
2020/06/02 Python
海淘母婴商城:国际妈咪
2016/07/23 全球购物
Troy-Bilt官网:草坪割草机、吹雪机、分蘖机等
2019/02/19 全球购物
写一个方法1000的阶乘
2012/11/21 面试题
How to spawning asynchronous work in J2EE
2016/08/29 面试题
怎样有效的进行自我评价
2013/10/06 职场文书
应用化学专业职业生涯规划书
2014/01/22 职场文书
2014保险公司个人工作总结
2014/12/09 职场文书
总经理助理岗位职责范本
2015/03/31 职场文书
apache ftpserver搭建ftp服务器
2022/05/20 Servers