Python使用openpyxl模塊處理Excel文件
首先貼出四種方法適用范圍比較:
注釋: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/
為什么把這三個(gè)一起說?
首先,xlutils封裝了xlrd xlwt,所以在使用前,會先下載這兩個(gè)依賴的模塊。
其次,這兩個(gè)模塊主要用于處理xls文件,而對xlsx的文件處理很挫,甚至xlwt不支持…
但為何到現(xiàn)在依然在使用這些模塊,因?yàn)樗麑ls文檔處理的優(yōu)勢….
1、xlutils
官方文檔:https://xlutils.readthedocs.io/en/latest/api.html
github項(xiàng)目:https://github.com/python-excel/xlutils
安裝:(如果沒安裝xlrd、xlwt,會自動安裝這2個(gè)模塊)
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項(xiàng)目: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項(xiàng)目:https://github.com/python-excel/xlwt
安裝:pip install xlwt
使用:用xlwt創(chuàng)建一個(gè)簡單的.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作為數(shù)據(jù)分析利器,在讀寫excel方面,依賴庫xlrd和xlwt。
import pandas as pd
#方法一:默認(rèn)讀取第一個(gè)表單
df=pd.read_excel('lemon.xlsx')#這個(gè)會直接默認(rèn)讀取到這個(gè)Excel的第一個(gè)表單
data=df.head()#默認(rèn)讀取前5行的數(shù)據(jù)
print("獲取到所有的值:\n{0}".format(data))#格式化輸出
#方法二:通過指定表單名的方式來讀取
df=pd.read_excel('lemon.xlsx',sheet_name='student')#可以通過sheet_name來指定讀取的表單
data=df.head()#默認(rèn)讀取前5行的數(shù)據(jù)
print("獲取到所有的值:\n{0}".format(data))#格式化輸出
#方法三:通過表單索引來指定要訪問的表單,0表示第一個(gè)表單
#也可以采用表單名和索引的雙重方式來定位表單
#也可以同時(shí)定位多個(gè)表單,方式都羅列如下所示
df=pd.read_excel('lemon.xlsx',sheet_name=['python','student'])#可以通過表單名同時(shí)指定多個(gè)
# 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])#可以通過索引 同時(shí)指定多個(gè)
data=df.values#獲取所有的數(shù)據(jù),注意這里不能用head()方法哦~
print("獲取到所有的值:\n{0}".format(data))#格式化輸出三、xlsxwriter
https://xlsxwriter.readthedocs.io/
xlsxwriter擁有豐富的特性,支持圖片/表格/圖表/篩選/格式/公式等,功能與openpyxl相似,優(yōu)點(diǎn)是相比 openpyxl 還支持 VBA 文件導(dǎo)入,迷你圖等功能,缺點(diǎn)是不能打開/修改已有文件,意味著使用 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.
最后要說說個(gè)人比較常用,也很方便的一個(gè)excel處理模塊openpyxl….這個(gè)模塊突出的優(yōu)勢在于,對excel單元格樣式的設(shè)置方面特別詳細(xì)。
注意:openpyxl不支持.xls格式。讀寫文件前記得多備注,有時(shí)候可能有bug。
官方文檔:https://openpyxl.readthedocs.io/en/stable/
安裝:pip install openpyxl
1、寫一個(gè)工作簿
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、讀取現(xiàn)有工作簿
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、使用樣式
樣式用于在屏幕上顯示時(shí)更改數(shù)據(jù)的外觀。它們還用于確定數(shù)字的格式。
樣式可以應(yīng)用于以下方面:
- 字體設(shè)置字體大小,顏色,下劃線等
- 填充以設(shè)置圖案或顏色漸變
- 邊框設(shè)置單元格上的邊框
- 單元格排列
- 保護(hù)
以下是默認(rèn)值:
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)到此這篇關(guān)于Python使用openpyxl模塊處理Excel文件的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 使用Python讀取和修改Excel文件(基于xlrd、xlwt和openpyxl模塊)
- Python3利用openpyxl讀寫Excel文件的方法實(shí)例
- python基于openpyxl生成excel文件
- 解決python執(zhí)行較大excel文件openpyxl慢問題
- Python3讀寫Excel文件(使用xlrd,xlsxwriter,openpyxl3種方式讀寫實(shí)例與優(yōu)劣)
- python 的 openpyxl模塊 讀取 Excel文件的方法
- Python使用openpyxl讀寫excel文件的方法
- python通過openpyxl生成Excel文件的方法
- Python 使用openpyxl處理Excel文件詳情
相關(guān)文章
Python 數(shù)據(jù)分析之逐塊讀取文本的實(shí)現(xiàn)
這篇文章主要介紹了Python 數(shù)據(jù)分析之逐塊讀取文本的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
pandas中遍歷dataframe的每一個(gè)元素的實(shí)現(xiàn)
這篇文章主要介紹了pandas中遍歷dataframe的每一個(gè)元素的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
python 實(shí)現(xiàn)圖像快速替換某種顏色
這篇文章主要介紹了python 實(shí)現(xiàn)圖像快速替換某種顏色,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
tensorflow建立一個(gè)簡單的神經(jīng)網(wǎng)絡(luò)的方法
本篇文章主要介紹了tensorflow建立一個(gè)簡單的神經(jīng)網(wǎng)絡(luò)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02
python實(shí)現(xiàn)登錄與注冊系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)登錄與注冊系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11

