Skip to content

Instantly share code, notes, and snippets.

@TomoG29
Created November 30, 2024 09:12
Show Gist options
  • Save TomoG29/8f19c4801bcd021e3d153d411a2b4025 to your computer and use it in GitHub Desktop.
Save TomoG29/8f19c4801bcd021e3d153d411a2b4025 to your computer and use it in GitHub Desktop.
import openpyxl
from openpyxl.utils.cell import coordinate_from_string, column_index_from_string
from openpyxl.styles import PatternFill
import os
import getpass
# 指定フォルダのパス
file_path = os.path.join("ファイルパス")
def main():
#############################################
# 1
#############################################
wb = openpyxl.load_workbook(file_path,data_only=True)
sheet = wb.active
#シートを変更する場合
#sheet = wb[タブ名 or インデックス番号]
print(wb.sheetnames)
#結果:['Sheet1']
#############################################
# 2
#############################################
start = 1
end = 10
#セルに追加(実数)
for i in range(start,end):
sheet.cell(row=i,column=1,value=i)
#セルに追加(数式)
sheet.cell(row=1,column=2,value=f"=SUM({sheet.cell(row=start,column=1).coordinate}:{sheet.cell(row=end,column=1).coordinate})")
#############################################
# 3
#############################################
#任意の列データを取得
column_num = "A"
column_data = [cell.value for cell in sheet[column_num]]
#任意の行データを取得
row_num = 1
row_data = [cell.value for cell in sheet[row_num]]
#openpyxl.utils.cellを使用した方法
cell = sheet.cell(row=1,column=1)
column_str = coordinate_from_string(cell.coordinate)[0]
use_utils_data = [cell.value for cell in sheet[column_str]]
print(column_data,row_data,use_utils_data,coordinate_from_string(cell.coordinate))
#############################################
# 4
#############################################
for i in range(start,end):
if sheet.cell(row=i,column=1).value % 2 == 0:
sheet.cell(row=i,column=1).fill = PatternFill(patternType='solid', fgColor='aaaaaa')
#############################################
# 5
#############################################
# Excelファイルを保存
wb.save(file_path)
wb.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment