1. 程式人生 > >Python--操作excel

Python--操作excel

range clas exce value .sh 操作 port tle col

import xlwt

# book = xlwt.Workbook() # 新建一個excel
# sheet = book.add_sheet(‘sheet1‘) # 添加一個sheet頁
# sheet.write(0, 0, ‘姓名‘)
# sheet.write(0, 1, ‘性別‘)
# sheet.write(0, 2, ‘年齡‘)
# book.save(‘stu.xls‘) # 微軟的office不能用xlsx結尾的,wps隨意
title = [‘姓名‘, ‘年齡‘, ‘性別‘, ‘分數‘]
stus = [[‘mary‘, 20, ‘女‘, 90], [‘mary‘, 20, ‘女‘, 89.9], [‘mary‘, 20, ‘女‘, 89.9], [‘mary‘, 20, ‘女‘, 89.9]]

book = xlwt.Workbook() # 新建一個excel
sheet = book.add_sheet(‘sheet1‘) # 添加一個sheet頁
cols = 0
for t in title:
sheet.write(0, cols, t)
cols += 1
row = 1 # 控制行
for stu in stus:
new_cols = 0
for s in stu: # 寫每一列
sheet.write(row, new_cols, s)
new_cols += 1
row += 1
book.save(‘stu1.xls‘)


import xlrd

book = xlrd.open_workbook(‘stu1.xls‘) # 打開一個excel
sheet = book.sheet_by_index(0) # 根據順序獲取sheet頁
# sheet1 = book.sheet_by_name(‘sheet1‘) # 根據sheet頁名字獲取
# print(sheet.cell(0, 0).value) # 指定行和列獲取數據
# print(sheet.cell(0, 1).value)
# print(sheet.cell(0, 2).value)

print(sheet.ncols) # 獲取excel裏面有多少列
print(sheet.nrows) # 獲取excel裏面有多少行

for i in range(sheet.nrows):
print(sheet.row_values(i)) # 取第幾行的數據

print(sheet.col_values(0)) # 取第幾列的數據


from xlutils.copy import copy
import xlrd


book1 = xlrd.open_workbook(‘stu1.xls‘)
book2 = copy(book1) # 拷貝一份原來的
sheet = book2.get_sheet(0) # 獲取第幾個sheet頁
sheet.write(1, 3, 0)
book2.save(‘stu1.xls‘)

Python--操作excel