(Windows 下操做) 先安裝一些處理 Excel 的模塊:python
1 pip install xlrd # 用於讀取Excel數據 2 pip install xlwt # 用於寫入Excel數據 3 pip install xlutils # 用於修改Excel數據
Python 讀取 Excel 數據:spa
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 讀取某一列數據: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()[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 表:code
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 讀取某一列數據:blog
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 表:ip
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 數據:utf-8
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文件