python 與excelpython
本例子中使用的模塊爲:ide
openpyxl函數
版本爲2.4.8工具
安裝方法請參看之前發表的文章(Python 的pip模塊安裝方法)字體
Python處理Excel表格excel
使用模塊:openpyxl(2.4.8)orm
1.首先導入模塊:import openpyxl對象
2.打開一個已經存在的excel文件:three
wb=openpyxl.load_workbook('example.xlsx')ip
(文件和腳本放在同一個目錄下,若是不是的話須要加上路徑
wb=wpenpyxl.load_workbook(r'c:\maxingpython\example.xlsx'))
此時wb是一個workbook對象,表示的是整個Excel文件,相似於file對象表示一個文本文件。
3.獲取Excel文件中具體的表:
sheet=wb.get_sheet_name('Sheet1')#根據表名獲取
sheet=wb[‘Sheet1’]#更簡潔的方法
sheet=wb.get_active_sheet()#獲取當前激活的表(即打開Excel默認打開的表)
sheet=wb.active#經過屬性獲取當前激活的表
Sheet.title能夠獲得表的名字。
4.獲取表中的行與列
sheet.rows
sheet.columns
注意這裏獲取的行與列是一個生成器對象:
>>> sheet.rows
5.獲取表的總行數與總列數
總行數:len(list(sheet.rows)) 總列數:len(list(sheet.columns))
直接調用屬性:sheet.max_row;sheet.max_column
6.獲取單元格對象
cell=sheet[‘A1’]#獲取了一個單元格對象
cell.value#獲取該單元格的值
這種方法是使用Excel種默認的行(數字)與列(字母)的形式來獲取對應的單元格。
另一種方式是直接指定命名參數:
cell=sheet.cell(row=2,column=2)
cell.value#獲取單元格的值
cell.row#獲取相應的行
cell.column#獲取相應的列
cell.cordinate#獲取相應的座標
>>> cell=sheet.cell(row=2,column=2)
>>> cell.value
'蘋果'
>>> cell.row
2
>>> cell.column
'B'
>>> cell.coordinate
'B2'
這種方法都是用數字來表示行與列(第一行爲1不是0)
這兩種工具互轉化:
>>> openpyxl.utils.cell.column_index_from_string('A')
1
>>> openpyxl.utils.cell.column_index_from_string('AC')
29
>>> openpyxl.utils.cell.get_column_letter(1)
'A'
>>> openpyxl.utils.cell.get_column_letter(29)
'AC'
>>>
7.獲取某一個區域的數據
>>> sheet['A1:C3']
((<cell 'sheet1'.a1="">, <cell 'sheet1'.b1="">, <cell 'sheet1'.c1="">), (<cell 'sheet1'.a2="">, <cell 'sheet1'.b2="">, <cell 'sheet1'.c2="">), (<cell 'sheet1'.a3="">, <cell 'sheet1'.b3="">, <cell 'sheet1'.c3="">))
>>> type(sheet['A1:C3'])
<class 'tuple'="">
>>> import pprint#上面打印太亂,導入漂亮打印模塊
>>> pprint.pprint(sheet['A1:C3'])
((<cell 'sheet1'.a1="">, <cell 'sheet1'.b1="">, <cell 'sheet1'.c1="">),
(<cell 'sheet1'.a2="">, <cell 'sheet1'.b2="">, <cell 'sheet1'.c2="">),
(<cell 'sheet1'.a3="">, <cell 'sheet1'.b3="">, <cell 'sheet1'.c3="">))
注意到sheet['A1:C3']獲取到的是一個元組組成的元組。
8.獲取全部的表名
>>> wb.get_sheet_names()
['my first sheet']
返回的是一個列表。
1.新建一個Excel文件
>>> from openpyxl import Workbook
>>> wb=Workbook()
>>> wb
這樣便建立了一個Workbook對象,實際上尚未生成Excel文件,要實際生成該Excel文件須要調用save函數以後。
默認Workbook對象將建立一張表「sheet」
>>> wb.active
<worksheet 'sheet'="">
>>> sheet=wb.active
>>> sheet.title='my first sheet'
>>> sheet.title
'my first sheet'
經過sheet.title屬性能夠修改表名。
2.保存
>>> wb.save('test.xlsx')
此時在工做目錄下才會生成test.xlsx文件。
3.增長及刪除表
>>> wb.create_sheet()
<worksheet 'sheet1'="">
>>> wb.get_sheet_names()
['Sheet', 'Sheet1']
>>> wb.create_sheet('names')
<worksheet 'names'="">
>>> wb.get_sheet_names()
['Sheet', 'Sheet1', 'names']
>>> wb.create_sheet(index=0,title='first tab')
<worksheet 'first="" tab'="">
>>> wb.get_sheet_names()
['first tab', 'Sheet', 'Sheet1', 'names']
>>> wb.create_sheet(index=len(wb.get_sheet_names()),title='last tab')
<worksheet 'last="" tab'="">
>>> wb.get_sheet_names()
['first tab', 'Sheet', 'Sheet1', 'names', 'last tab']
>>> wb.remove_sheet(wb['first tab'])
>>> wb.get_sheet_names()
['Sheet', 'Sheet1', 'names', 'last tab']
4.向單元格中寫入信息
>>> sheet['A1']='Hello world!'
>>> sheet.cell(row=2,column=2).value='張三'
>>> sheet['B2'].value
'張三'
5.單元格字體風格
首先要導入相應的函數:
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)
>>>
例子:
爲單元格設置樣式
>>> cell1=sheet['A1']
>>> cell2=sheet['A2']
>>> ft1=Font(color=colors.RED)
>>> ft2=Font(color='00FF00',size=30)
>>> cell1.font=ft1
>>> cell2.font=ft2
複製樣式:
>>> fromopenpyxl.stylesimportFont
>>> fromcopyimportcopy
>>>
>>> ft1=Font(name='Arial', size=14)
>>> ft2=copy(ft1)
>>> ft2.name='Tahoma'
>>> ft1.name'Arial'
>>> ft2.name'Tahoma'
>>> ft2.size# copied from the14.0
自定義樣式:
>>> from openpyxl.styles import NamedStyle, Font, Border, Side
>>> highlight = NamedStyle(name='highlight')
>>> highlight.font = Font(bold=True, size=20)
>>> bd = Side(style='thick', color='000000')
>>> highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
建立好後即可以應用到workbook了
>>> wb.add_named_style(highlight)#第一步
>>> ws['A1'].style = highlight#第二步
Once registered assign the style using just the name:
>>> ws['D5'].style = 'highlight'#之後就能夠直接調用字符串形式了
7.合併與拆分單元格
import openpyxl
wb=openpyxl.load_workbook('two.xlsx')
sheet=wb.active
sheet.merge_cells('A1:A2')
wb.save('three.xlsx')
同理拆開單元格即是sheet.unmerge_cells('A1:A2'),可是在交互式環境中能夠,寫在py文件中就會報錯,不知什麼緣由。