1. 程式人生 > >python對excel的操作

python對excel的操作

xlutils 新建 取數據 color nbsp 保存 int utils 導入

1.寫操作

import xlwt
#只能寫不能讀
stus = [[姓名, 年齡, 性別, 分數],
        [mary, 20, , 89.9],
        [mary, 20, , 89.9],
        [mary, 20, , 89.9],
        [mary, 20, , 89.9]
        ]
book = xlwt.Workbook()#新建一個excel
sheet = book.add_sheet(case1_sheet)#添加一個sheet頁
row = 0#控制行
for stu in
stus: col = 0#控制列 for s in stu:#再循環裏面list的值,每一列 sheet.write(row,col,s) col+=1 row+=1 book.save(stu_1.xls)#保存到當前目錄下

2.讀操作

import xlrd
#只能讀不能寫
book = xlrd.open_workbook(stu.xls)#打開一個excel
sheet = book.sheet_by_index(0)#根據順序獲取sheet
sheet2 = book.sheet_by_name(case1_sheet
)#根據sheet頁名字獲取sheet print(sheet.cell(0,0).value)#指定行和列獲取數據 print(sheet.cell(0,1).value) print(sheet.cell(0,2).value) print(sheet.cell(0,3).value) print(sheet.ncols)#獲取excel裏面有多少列 print(sheet.nrows)#獲取excel裏面有多少行 print(sheet.get_rows())# for i in sheet.get_rows(): print(i)#獲取每一行的數據 print(sheet.row_values(0))#
獲取第一行 for i in range(sheet.nrows):#0 1 2 3 4 5 print(sheet.row_values(i))#獲取第幾行的數據 print(sheet.col_values(1))#取第一列的數據 for i in range(sheet.ncols): print(sheet.col_values(i))#獲取第幾列的數據

3.修改操作

from xlutils.copy import copy #從xlutils模塊導入copy
import xlrd
book1 = xlrd.open_workbook(stu.xls) #得到Excel文件的book對象,實例化對象
book2 = copy(book1) #拷貝一份原來的excel
sheet = book2.get_sheet(0) #獲取第幾個sheet頁
sheet.write(1,3,0) #對拷貝的excel第2行,第4列數據為0
sheet.write(1,0,小黑) #對拷貝的excel第2行,第1列數據為小黑
book2.save(stu.xls) #保存修改後excel

python對excel的操作