標籤:blog pip nbsp 檔案的 .sh write excel表格 value xls
(Windows 下操作) 先安裝一些處理 Excel 的模組:
1 pip install xlrd # 用於讀取Excel資料2 pip install xlwt # 用於寫入Excel資料3 pip install xlutils # 用於修改Excel資料
Python 讀取 Excel 資料:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlrd 5 6 def readExcel(): 7 data = xlrd.open_workbook(‘1.xlsx‘) # 開啟一個Excel表格 8 table = data.sheets()[0] # 開啟Excel表格的第一張表 9 nrows = table.nrows # 擷取每張表的行數10 for line in range(nrows): # 遍曆每一行11 print(table.row_values(line)) # 擷取每行的值12 13 if __name__ == "__main__":14 readExcel()
[‘姓名‘, ‘性別‘, ‘年齡‘][‘小明‘, ‘男‘, 17.0][‘小紅‘, ‘女‘, 18.0][‘小李‘, ‘男‘, 19.0][‘小張‘, ‘男‘, 20.0]
Python 讀取某一列資料:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlrd 5 6 def readExcel(): 7 data = xlrd.open_workbook(‘1.xlsx‘) # 開啟一個Excel表格 8 table = data.sheets()[1] # 開啟excel表格的第一張表 9 ncols = table.ncols # 擷取每張表的列數10 for col in range(ncols): # 遍曆每一列11 print(table.col_values(col)[0]) # 擷取第一列的值12 13 if __name__ == "__main__":14 readExcel()
Python 建立 Excel 表:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlwt 5 6 excel = xlwt.Workbook() # 建立一個Excel檔案 7 sheet1 = excel.add_sheet("sheet1") # 添加一張表,表名為"sheet1" 8 sheet1.write(0, 0, "Name") # 表示在第一行第一列寫入內容"Name" 9 sheet1.write(1, 0, "John") # 表示在第二行第一列寫入內容"John"10 sheet1.write(2, 0, "Jeny") # 表示在第三行第一列寫入內容"Jeny"11 excel.save("1.xls") # 儲存Excel檔案,並命名為"1.xls"
Python 讀取某一列資料:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlrd 5 6 def readExcel(): 7 data = xlrd.open_workbook(‘1.xlsx‘) # 開啟一個Excel表格 8 table = data.sheets()[1] # 開啟excel表格的第一張表 9 ncols = table.ncols # 擷取每張表的列數10 for col in range(ncols): # 遍曆每一列11 print(table.col_values(col)[0]) # 擷取第一列的值12 13 if __name__ == "__main__":14 readExcel()
Python 建立 Excel 表:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlwt 5 6 excel = xlwt.Workbook() # 建立一個Excel檔案 7 sheet1 = excel.add_sheet("sheet1") # 添加一張表,表名為"sheet1" 8 sheet1.write(0, 0, "Name") # 表示在第一行第一列寫入內容"Name" 9 sheet1.write(1, 0, "John") # 表示在第二行第一列寫入內容"John"10 sheet1.write(2, 0, "Jeny") # 表示在第三行第一列寫入內容"Jeny"11 excel.save("1.xls") # 儲存Excel檔案,並命名為"1.xls"
Python 修改 Excel 資料:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import xlrd 5 import xlutils.copy 6 7 data = xlrd.open_workbook(‘1.xls‘) # 開啟一個Excel檔案 8 excel = xlutils.copy.copy(data) # 相當於複製Excel檔案,然後在複製的檔案上操作 9 sheet1 = excel.get_sheet(0) # 擷取要修改的表(這裡我修改Excel檔案的第一張表)10 sheet1.write(2, 0, ‘Tom‘) # 表示把第三行第一列的資料修改為‘Tom‘11 excel.save(‘1.xls‘) # 儲存Excel檔案
day53——Python 處理 Excel 資料