(一) 使用cell()函數來設定儲存格的值,可以以下語法:ws.cell(row = 列數,column = 行數,value = 值)
或是ws.cell(row = 列數,column = 行數).value = 值
例如:設定3列2行的值是10ws.cell(row = 3,column = 2,value = 10)
ws.cell(row = 3,column = 2).value = 10
#ch2_3.py
import openpyxl
from openpyxl.styles import Font
import os
# 切換到指定路徑
os.chdir(r"C:\Catherine_Files")
wb = openpyxl.Workbook() #建立空白wb
ws = wb.active
ws.cell(row = 2,column = 1,value = 'Apple')
ws.cell(row = 3,column = 1,value = 'Banana')
ws.cell(row = 2,column = 2,value = 200)
ws.cell(row = 3,column = 2,value = 150)
wb.save('out2_3.xlsx') #儲存wb
(二) 使用cell()函數來取得儲存格的值,可以以下語法:data = ws.cell(row = 列數,column = 行數).value
相當於cell()函數內省略value參數設定,而是用了value屬性取得特定函數內容
#ch2_4.py
import openpyxl
from openpyxl.styles import Font
import os
os.chdir(r"C:\Catherine_Files")
# os.chdir 是 python 切換到電腦指定路徑的方法
fn = "out1_4.xlsx"
wb = openpyxl.load_workbook(fn) #開啟wb
ws = wb.active
print("A1 = ", ws.cell(row =1, column = 1).value)
print("A2 = ", ws.cell(row =2, column = 1).value)
print("B1 = ", ws.cell(row =1, column = 2).value)
print("B2 = ", ws.cell(row =2, column = 2).value)
可以直接回傳我想看到的資訊