1. 程式人生 > 其它 >【Python模組】os, time, openpyxl

【Python模組】os, time, openpyxl

from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook

import os
import time
import random

"""
openpyxl(可讀寫excel表)專門處理Excel2007及以上版本產生的xlsx檔案,
xls和xlsx之間轉換容易 注意:如果文字編碼是“gb2312” 讀取後就會顯示亂碼,
請先轉成Unicode
"""

def writeExcel():
    print(os.getcwd())
    excelPath = os.path.join(os.getcwd(), 'ExcelData')
    print("****"*20)
    print(excelPath)
    nameTime = time.strftime('%Y-%m-%d_%H-%M-%S')
    excelName = 'Excel' + nameTime + '.xlsx'
    ExcelFullName = os.path.join(excelPath, excelName)
    print(ExcelFullName)

    wb = Workbook()#Workbook()構建器建立一個workbook(wb)

    ws = wb.active #ws應該是工作薄wb(workbook)的當前工作ws(worksheet)
    #表頭
    tableTitle = ['userName', 'Phone', 'age', 'Remark']

    for col in range(len(tableTitle)):
        c = col + 1
        ws.cell(row=1, column=c).value = tableTitle[col]#cell應該是單元格

    tableValues = [['張學友', 15201062100, 18, '測試資料!'],
                   ['李雷', 15201062598, 19, '測試資料!'],
                   ['Marry', 15201062191, 28, '測試資料!']]

    for row in range(len(tableValues)):
        ws.append(tableValues[row])
    """
    ws.append(iterable)
    #新增一行到當前sheet的最底部(即逐行追加從第一行開始) iterable必須是:
    list,tuple,dict,range,generator型別的。 1,如果是list,將list從頭到
    尾順序新增。 2,如果是dict,按照相應的鍵新增相應的鍵值。
    """
    wb.save(filename=ExcelFullName)#workbook 呼叫save()方法儲存
    return ExcelFullName

def readExcel(ExcelFullName):
    wb = load_workbook(ExcelFullName)

    # sheets = wb.get_sheet_names()
    sheets = wb.sheetnames
    print(sheets)
    sheet_first = sheets[0]

    # ws = wb.get_sheet_by_name(sheet_first)
    ws = wb[sheet_first]#相當於通過字典的鍵獲取值
    print("***")
    print(sheet_first)
    print(ws.title)
    print("^^^")

    rows = ws.rows
    print(rows)
    # print(f"rows = {list(rows)}")
    list1 = []
    for row in list(rows):
        case = []
        for c in row:
            case.append(c.value)
        print(f"case= {case}")
        list1.append(case)

    print(list1)
        #combine the lists into one nested list


    columns = ws.columns

    # for row in rows:
    #     line = [col.value for col in row]
    #     print("line is: *** ")
    #     print(line)
    # print("ws[A1]: ")
    # print(ws['A1'].value)
    # print("cell(row=1, column=1): ")
    # print(ws.cell(row=1, column=1).value)
    # print(ws.max_row)
    # print(ws.max_column)
"""
通俗的理解__name__ == '__main__':假如你叫小明.py,在朋友眼中,你是小明(__name__ == '小明');在你自己眼中,你是你自己(__name__ == '__main__')。
if __name__ == '__main__'的意思是:當.py檔案被直接執行時,if __name__ == '__main__'之下的程式碼塊將被執行;當.py檔案以模組形式被匯入時,if __name__ == '__main__'之下的程式碼塊不被執行。
"""
if __name__ == '__main__':
    ExcelFullName = writeExcel()
    readExcel(ExcelFullName)