這篇文章主要介紹“Python如何使用openpyxl模塊處理Excel文件”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Python如何使用openpyxl模塊處理Excel文件”文章能幫助大家解決問題。
首先貼出四種方法適用范圍比較:
注釋:Excel 2003 即XLS文件有大小限制即65536行256列,所以不支持大文件。而Excel 2007以上即XLSX文件的限制則為1048576行16384列
最原始的莫過于兩位老牌黃金搭檔xlrd xlwt了,針對二者的封裝有如下模塊:
xlutils
xlrd
xlwt
為什么把這三個一起說?
首先,xlutils封裝了xlrd xlwt,所以在使用前,會先下載這兩個依賴的模塊。
其次,這兩個模塊主要用于處理xls文件,而對xlsx的文件處理很挫,甚至xlwt不支持…
但為何到現在依然在使用這些模塊,因為他對xls文檔處理的優勢….
安裝:(如果沒安裝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')
安裝: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))
安裝: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作為數據分析利器,在讀寫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擁有豐富的特性,支持圖片/表格/圖表/篩選/格式/公式等,功能與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()
讀寫 Excel 2010 xlsx/xlsm files.
最后要說說個人比較常用,也很方便的一個excel處理模塊openpyxl….這個模塊突出的優勢在于,對excel單元格樣式的設置方面特別詳細。
注意:openpyxl不支持.xls格式。讀寫文件前記得多備注,有時候可能有bug。
安裝:pip install openpyxl
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)
from openpyxl import load_workbook wb = load_workbook(filename = 'empty_book.xlsx') sheet_ranges = wb['Sheet1'] print(sheet_ranges['D18'].value)
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')
樣式用于在屏幕上顯示時更改數據的外觀。它們還用于確定數字的格式。
樣式可以應用于以下方面:
字體設置字體大小,顏色,下劃線等
填充以設置圖案或顏色漸變
邊框設置單元格上的邊框
單元格排列
保護
以下是默認值:
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文件”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。