Python操作Excel文件
Excel讀取:
# 導入模塊 import xlrd #這個模塊不是python,需要下載安裝,直接按快捷鍵Alt+Shift+Enter,PyCharm會自動安裝 # 讀取到excel文件 data = xlrd.open_workbook("xxx.xlsx") # 獲取列表 table = data.sheet_by_index(0) # 獲取所有的行數 nrows = table.nrows # # 獲取所有的列數 # ncols = table.ncols # 獲取第一行的數據 first_row_name_list = table.row_values(0) print(first_row_name_list) # 定義一個列表保存所有行的數據 info_list = [] # 遍歷所有行 for rownum in range(1, nrows): # 獲取 row = table.row_values(rownum) # 如果row有數據 if row: info_list.append(row) print(info_list)
Excel寫入:
# 導入模塊 import xlsxwriter #這個模塊不是python,需要下載安裝,直接按快捷鍵Alt+Shift+Enter,PyCharm會自動安裝 # 打開student.xlsx文件 workbook = xlsxwriter.Workbook("student.xlsx") # 創建一張工作表 worksheet = workbook.add_worksheet() # 設置第一行信息 worksheet.write(0, 0, "學號") worksheet.write(0, 1, "姓名") worksheet.write(0, 2, "年齡") # 學生信息列表 student_list = [{"name": "小A", "age": 20, "no": "no1"}, {"name": "小B", "age": 21, "no": "no2"}, {"name": "小C", "age": 20, "no": "no3"}, {"name": "小D", "age": 23, "no": "no4"}, {"name": "小E", "age": 25, "no": "no5"}] # 遍歷列表 for i, info in enumerate(student_list): # 寫入數據 # write(第x行, 第x列, 寫入的數據) worksheet.write(i + 1, 0, info["no"]) worksheet.write(i + 1, 1, info["name"]) worksheet.write(i + 1, 2, info["age"]) # 關閉文件 workbook.close()

浙公網安備 33010602011771號