標籤:auth 定義 direct opened 命名 rop xlsx property image
openpyxl 可以很好的處理 2010版本以上的表格。
樣本:
1 #coding:utf8 2 ‘‘‘ 3 Created on 2018年8月18日 4 5 @author: Administrator 6 ‘‘‘ 7 from openpyxl import Workbook 8 import datetime 9 wb = Workbook()10 11 # grab the active worksheet12 ws = wb.active13 14 # Data can be assigned directly to cells15 ws[‘A1‘] = "班級人員統計表"16 17 # Rows can also be appended18 list_str=["記錄時間","學號","姓名","性別","年齡"]19 ws.append(list_str)20 21 list_str2=["1","諸葛亮","男","89"]22 time1=datetime.date.today()23 list_str2.insert(0, time1)24 ws.append(list_str2)25 26 # 如果你要在已經有的資料上進行修改,會自動覆蓋掉,原有的資料27 # import datetime28 # ws[‘A2‘] = datetime.datetime.now()29 30 # Save the file31 wb.save("sample.xlsx")在記憶體中處理一個活頁簿:建立一個活頁簿
沒有必要利用 openpyxl 先去建立一個檔案系統上的檔案然後才能開始使用。你只要匯入活頁簿類,然後開始使用它吧。
>>> from openpyxl import Workbook>>> wb = Workbook()
A workbook is always created with at least one worksheet. You can get it by using the openpyxl.workbook.Workbook.active() property
一個活頁簿被建立後,總會在裡面預設建立一張工作表。你可以通過使用方法 openpyxl.workbook.Workbook.active() 來得到它。
ws = wb.active
預設狀態下,函數 the _active_sheet_index property 的 index設定為0,除非你手動修改它的數值,否則的話,你用這個方法,只會拿到第一個工作表。
1 @property 2 def active(self): 3 """Get the currently active sheet or None 4 5 :type: :class:`openpyxl.worksheet.worksheet.Worksheet` 6 """ 7 try: 8 return self._sheets[self._active_sheet_index] 9 except IndexError:10 pass11 12 @active.setter13 def active(self, value):14 """Set the active sheet"""15 self._active_sheet_index = value16 17 def create_sheet(self, title=None, index=None):18 """Create a worksheet (at an optional index).19 20 :param title: optional title of the sheet21 :type title: unicode22 :param index: optional position at which the sheet will be inserted23 :type index: int24 25 """26 if self.read_only:27 raise ReadOnlyWorkbookException(‘Cannot create new sheet in a read-only workbook‘)28 29 if self.write_only :30 new_ws = WriteOnlyWorksheet(parent=self, title=title)31 else:32 new_ws = Worksheet(parent=self, title=title)33 34 self._add_sheet(sheet=new_ws, index=index)35 return new_ws
View Code
可以通過 openpyxl.workbook.Workbook.create_sheet() 方法,建立工作表。
wb.create_sheet("mysheet", 1)wss=wb.create_sheet()ws1 = wb.create_sheet("Mysheet111") # insert at the end (default)ws2 = wb.create_sheet("Mysheet222", 0) # insert at first position
工作表的名字是自動命令。按照列表(Sheet, Sheet1, Sheet2, …)的內容,順序命名。你也可以自訂工作表名字。
ws.title = "New Title"
預設情況下,包含此標題的選項卡的背景顏色為白色。您可以將此更改為為 sheet_properties 提供RRGGBB顏色代碼。 tabColor 屬性:
ws.sheet_properties.tabColor = "1072BA"
Python處理Excel文檔之openpyxl