python之openpyxl介紹(讀寫excel)


讀寫excel比較方便。並且支持xlsx格式的處理。網上也存在一些這方面的介紹,但是版本更新了多次,部分內容不適用

版本:openpyxl 2.5.1

 

  1. 讀: 方法:獲取工作簿:openpyxl.load_workbook("20181.xlsx")

獲取工作薄的工作表,Sheet1為新建的sheet名:ws=wb["Sheet1"]

 

wb.active:不寫其實也可以

  1. 寫:wb=workbook()# 新增一個新excel
寫入單元格:ws["A1"]=31
寫入sheet名稱:ws.title='AAAA'
  1. 讀寫:

 

#coding:utf-8
import openpyxl
wb=openpyxl.load_workbook("20181.xlsx")
wb.active
ws=wb["Sheet1"]
ws["A1"]=31
wb.save("20181.xlsx")#保存

 

wb.save("20181.xlsx")#保存
打開文檔后,
  1. 其他:


#coding=utf-8
# python 處理excel的第三方庫有:xlrd(讀excel)、xlwd(寫excel)、openpyxl(讀寫excel)
#比較難纏的問題:unicode編碼和excel中記錄的時間
import openpyxl


workbook=openpyxl.load_workbook(r"2018.xlsx")
ws=workbook.active
print (ws.title)
# 讀取一行或者一列
for cell in ws['1']:#行
# for cell in ws['A']:#列
    if cell.coordinate=='BB1':
        break
    print(cell.coordinate,cell.value) #coordinate 坐標
# worksheets=workbook.get_sheet_names()# 獲取所有sheet名稱,方法已廢棄
worksheets=workbook.sheetnames#方法當屬性用@property

# sheet=workbook.get_sheet_by_name(worksheets[1])#獲取/激活一個工作表,方法已廢棄
sheet=workbook[worksheets[1]]#獲取/激活一個工作表

# 兩種讀取方式
print sheet['B1'],sheet['B1'].value
print sheet.cell(row=1,column=2).value
獲取最大行數
print(sheet.max_row,sheet.max_column)

# 查詢統計表的名稱
for r in range(1,sheet.max_row-1):
    name=sheet.cell(row=r, column=2).value
    value=sheet.cell(row=r, column=sheet.max_column-1).value
    if not isinstance(value,long) :#判斷類型
        print 'pass'
    print name,value
# 字母和數字之間轉換
from openpyxl.utils import get_column_letter,column_index_from_string
print get_column_letter(1)
print get_column_letter(11)
print column_index_from_string('A')

#獲取A2:B4 單元格區域
print '************************************'
print tuple(sheet["A2":"B4"])
for rowOfCell in sheet["A2":"B4"]:
    for temp in rowOfCell:
        if __name__ == '__main__':
            print temp.coordinate,temp.value

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM