1. 程式人生 > >Python學習筆記(十)——處理Excel電子表格

Python學習筆記(十)——處理Excel電子表格

安裝openpyxl模組

pip install openpyxl

讀取Excel檔案

用openpyxl模組開啟Excel文件

>>> wb = openpyxl.load_workbook('temp.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>

從工作簿取得工作表

get_sheet_names()
get_sheet_by_name('Sheet3')
get_sheet_by_name('Sheet3')

>>> wb.get_sheet_names()
['Sheet1'
, 'Sheet2', 'Sheet3'] >>> sheet = wb.get_sheet_by_name('Sheet3') >>> sheet <Worksheet "Sheet3"> >>> type(sheet) <class 'openpyxl.worksheet.worksheet.Worksheet'> >>> sheet.title 'Sheet3' >>> anotherSheet = wb.get_sheet_by_name('Sheet3') >>> anotherSheet <Worksheet "Sheet3"
>

從表中獲取單元格

>>> import openpyxl
>>> wb = openpyxl.load_workbook('temp.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet['B1']
<Cell 'Sheet3'.B1>
>>> sheet['B1'
].value '10點06分' >>> '現在是' + str(sheet['C1'].value) + '上午' + str(sheet['B1'].value) '現在是43141上午10點06分' >>> '現在是' + str(sheet['C1'].value) + '上午' + str(sheet['B1'].value) '現在是43141上午10點06分'
>>> 'ROW' + str(sheet['B1'].row) + 'Column ' + str(sheet['B1'].column) + 'is' + str(sheet['B1'].value)
'ROW1Column Bis10點06分'
>>> 'ROW ' + str(sheet['B1'].row) + ' Column ' + str(sheet['B1'].column) + ' is ' + str(sheet['B1'].value)
'ROW 1 Column B is 10點06分'
>>> sheet['B1'].coordinate
'B1'
>>> sheet.cell(row=1,column=2)
<Cell 'Sheet3'.B1>
>>> sheet.cell(row=1,column=2).value
'10點06分'
>>> for i in range(1,8,2):
    print(i,sheet.cell(row = i , column = 2).value)


1 10063 10085 10107 1012
>>> sheet.max_row
7
>>> sheet.max_column
4

列表字母轉換

>>> import openpyxl
>>> try:
    from openpyxl.cell import get_column_letter,column_index_from_string
except ImportError:
    from openpyxl.utils import get_column_letter,column_index_from_string

>>> get_column_letter(27)
'AA'
>>> wb = openpyxl.load_workbook('temp.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> get_column_letter(sheet.max_column)
'D'
>>> column_index_from_string('AAA')
703

從表中獲取行和列

>>> wb = openpyxl.load_workbook('temp.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet3')

Warning (from warnings module):
  File "__main__", line 1
DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
>>> tuple(sheet['B1':'D7'])
((<Cell 'Sheet3'.B1>, <Cell 'Sheet3'.C1>, <Cell 'Sheet3'.D1>), (<Cell 'Sheet3'.B2>, <Cell 'Sheet3'.C2>, <Cell 'Sheet3'.D2>), (<Cell 'Sheet3'.B3>, <Cell 'Sheet3'.C3>, <Cell 'Sheet3'.D3>), (<Cell 'Sheet3'.B4>, <Cell 'Sheet3'.C4>, <Cell 'Sheet3'.D4>), (<Cell 'Sheet3'.B5>, <Cell 'Sheet3'.C5>, <Cell 'Sheet3'.D5>), (<Cell 'Sheet3'.B6>, <Cell 'Sheet3'.C6>, <Cell 'Sheet3'.D6>), (<Cell 'Sheet3'.B7>, <Cell 'Sheet3'.C7>, <Cell 'Sheet3'.D7>))
>>> for temp in sheet['B1':'D7']:
    for tempp in temp:
        print(tempp.coordinate,tempp.value)
    print('---END---')


B1 10點06分
C1 二〇一八年二月十日
D1 75
---END---
B2 10點07分
C2 二〇一八年二月十日
D2 80
---END---
B3 10點08分
C3 二〇一八年二月十日
D3 85
---END---
B4 10點09分
C4 二〇一八年二月十日
D4 90
---END---
B5 10點10分
C5 二〇一八年二月十日
D5 95
---END---
B6 10點11分
C6 二〇一八年二月十日
D6 100
---END---
B7 10點12分
C7 二〇一八年二月十日
D7 105
---END---
>>> sheet['A']
(<Cell 'Sheet3'.A1>, <Cell 'Sheet3'.A2>, <Cell 'Sheet3'.A3>, <Cell 'Sheet3'.A4>, <Cell 'Sheet3'.A5>, <Cell 'Sheet3'.A6>, <Cell 'Sheet3'.A7>)
>>> sheet['1']
(<Cell 'Sheet3'.A1>, <Cell 'Sheet3'.B1>, <Cell 'Sheet3'.C1>, <Cell 'Sheet3'.D1>)
>>> 

小實驗——從電子表格中讀取資料

#! python3
#readExcel.py 
#
#Author : qmeng
#MailTo : [email protected]
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/
#Create : 2018-02-010
#Version: 1.0
#
import openpyxl,pprint,os
print('Opening workbook...')
wb = openpyxl.load_workbook('2017.xlsx')
sheet = wb.get_sheet_by_name('Sheet0')
Data = {}
print('Reading rows...')
for row in range(3,sheet.max_row+1):
    Num      = sheet['B'+str(row)].value
    Name     = sheet['E'+str(row)].value
    sProject = sheet['F'+str(row)].value
    eProject = sheet['G'+str(row)].value

    #填充資料結構
    #Data.setdefault(Num,{Name:'',sProject:'',eProject:''})
    Data[Num] = {'Name':Name,'sProject':sProject,'eProject':eProject}
    #print(Name + ' 同學資訊載入完畢...')
print('Writing results...')
File = open('abcdef.py','w')
File.write('allData = ' + pprint.pformat(Data))
File.close()
print('Done...')

#import abcdef
#>>> abcdef.allData['2017000349']
#{'Name': '18834198699', 'eProject': '9/933', 'sProject': 4.28}

寫入Excel文件

簡書

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb.get_active_sheet()
>>> sheet.title
'Sheet'
>>> sheet.title = 'first'
>>> sheet['A1'] = '123456'
>>> wb.save('example.xlsx')

小實驗——更新一個電子表格

#! python3
#updateProduce.py - 
#Usage:
#
#Author : qmeng
#MailTo : [email protected]
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/
#Create : 2018-02-10 15:42:18
#Version: 1.0
#
import openpyxl
wb = openpyxl.load_workbook('temp.xlsx')
sheet = wb.get_sheet_by_name('Sheet3')
UPDATA = {'10點06分':'200',
            '10點07分':'300',
            '10點08分':'400'}
print(sheet.max_row)
for row1 in range(sheet.max_row):
        if sheet.cell(row = row1,column = 2)value in UPDATA.keys():
                sheet['D'+str(roe)] = UPDATA[sheet['B'+str(row)].value]
                print(sheet['B'+str(row)].value)
wb.save('temp.xlsx')

相關推薦

Python學習筆記——處理Excel電子表格

安裝openpyxl模組 pip install openpyxl 讀取Excel檔案 用openpyxl模組開啟Excel文件 >>> wb = openpyxl.load_workbook('temp.x

Python學習筆記

類型 property 獲取 bsp 構造 屬性 增加 函數類 pro 一、類和構造函數的定義   class 類名(object):    def __init__(self,name,score):      self.name = name      self.sco

day5-Python學習筆記常用模塊

stat 結果 fig .get 文件顯示 刪除空文件 conf std 分割 import os# print(os.getcwd())#取當前工作目錄# print(os.chdir("..")) # 更改當前目錄# print(os.getcwd())#取當前工作目

Python學習筆記高階變數型別--列表

Python中資料型別可以分為 數字型和 非數字型 數字型 整形(int) 浮點型(float) 布林型(bool)     真 True 非 0 數——非零即真     假 False 0

python 學習筆記: 資料庫連線池

#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import Queue import pymysql import logging LOG =

python學習筆記異常處理

關鍵字 .exe strip support 異常 解析器 輸入 rod () python解析器去執行程序,檢測到了一個錯誤時,觸發異常,異常觸發後且沒被處理的情況下,程序就在當前異常處終止,後面的代碼不會運行,所以你必須提供一種異常處理機制來增強你程序的健壯性與容錯性

Python學習筆記——處理PDF密碼破解

#! python3 #UnlockPDF.py - #Usage: # #Author : qmeng #MailTo : [email protected] #QQ : 1163306125 #Blog : http://blog.c

Python學習筆記裝飾器

before 原來 return wrap 文本 wiki 模塊 http 學習筆記 摘抄:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318

Python學習筆記 使用模塊

常見 永遠 命令行 效果 學習筆記 例如 style name hello 摘抄:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431845183

Python學習筆記Python獲取本地數據

cname lin txt .py ora 系統 筆記 緩沖 log f1 = open(r‘E:\Python\Data\data1.txt‘) #讀取data1.txt文件,使用系統默認緩沖區大小, 為了讀取快點,使用緩存吧!

Python學習筆記拓展庫Scipy

mage http 十六 .cn 學習筆記 eight -1 images 分享 Python學習筆記(十六)拓展庫Scipy

Python學習筆記@property

assert value 復雜 blog 只讀 self %d idt 學習 # [email protected]/* */, # 以及一個只讀屬性resolution: # -*- coding: utf-8 -*- class Screen(

Python學習筆記

def __init__ 實現 完成 cti uniq ive 枚舉 elf 一、Python的多重繼承功能   Python中的主線是單一繼承的   Python中可以存在功能類,即專註於完成一定功能的類,相當於其他一些動態語言中的接口的概念   class Class_

Python學習筆記

check target 哈哈 方法 多個 multi 定義 輸出 poll 一、進程與線程   一個操作系統可以有多個進程  一個進程可以有多個線程,且必須有一個線程 二、多進程   from multiprocessing import Process  import

Python學習筆記

插入 imp 集合類 屬性 counter 以及 雙向 ror 簡單的 一、collections介紹   collections是Python中內建的一個集合模塊,提供了許多有用的集合類 二、namedtuple   namedtuple是一個函數,用來創建一個類似類的自

Python學習筆記

一個 模式 時間模塊 dal 同名 學習 日期時間 mda dst 一、datetime簡介   datetime是Python處理日期和時間的標準庫 二、導入datetime日期時間處理標準庫   # datetime是日期時間模塊,其中包括一個同名的日期時間類  fro

python學習筆記之函數

last 函數返回 traceback keep disco show 全局變量 not 默認參數 牛刀小試:   定義一個無參函數 1 >>> def myFirstFunc(): 2 ... print("Hello python

python學習筆記之集合

head erro sdi pytho not in 註意 inter ren mod 集合:對應數學中的集合類型。集合中的元素是唯一,且無序的。 創建集合   方法一:使用{},註意python會自動刪除重復元素 >>> number = {1,2,3

day7-Python學習筆記網絡編程

http on() 學習 int jni 二進制格式 size users -s import urllib.requestimport json,requests#發送get請求# url = ‘http://api.nnzhp.cn/api/user/stu_info?

python學習筆記面向對象編程,類

時代 alt 類名 rst tps 玉溪 connect nbsp nco 一、面向對象編程 面向對象,是一種程序設計思想。 編程範式:編程範式就是你按照什麽方式去編程,去實現一個功能。不同的編程範式本質上代表對各種類型的任務采取的不同的解決問題的思路,兩種最重要的編程範式