python3 對excel讀、寫、修改的操作


一、對excel的寫操作實例:

將一個列表的數據寫入excel, 第一行是標題,下面行數具體的數據

 1 import xlwt
 2 #只能寫不能讀
 3 stus = [['姓名', '年齡', '性別', '分數'],
 4         ['mary', 20, '', 89.9],
 5         ['mary', 20, '', 89.9],
 6         ['mary', 20, '', 89.9],
 7         ['mary', 20, '', 89.9]
 8         ]
 9 book = xlwt.Workbook()#新建一個excel
10 sheet = book.add_sheet('case1_sheet')#添加一個sheet頁
11 row = 0#控制行
12 for stu in stus:
13     col = 0#控制列
14     for s in stu:#再循環里面list的值,每一列
15         sheet.write(row,col,s)
16         col+=1
17     row+=1
18 book.save('stu_1.xls')#保存到當前目錄下

二、對excel 的讀操作:

 1 import xlrd
 2 #只能讀不能寫
 3 book = xlrd.open_workbook('stu.xls')#打開一個excel
 4 sheet = book.sheet_by_index(0)#根據順序獲取sheet
 5 sheet2 = book.sheet_by_name('case1_sheet')#根據sheet頁名字獲取sheet
 6 print(sheet.cell(0,0).value)#指定行和列獲取數據
 7 print(sheet.cell(0,1).value)
 8 print(sheet.cell(0,2).value)
 9 print(sheet.cell(0,3).value)
10 print(sheet.ncols)#獲取excel里面有多少列
11 print(sheet.nrows)#獲取excel里面有多少行
12 print(sheet.get_rows())#
13 for i in sheet.get_rows():
14     print(i)#獲取每一行的數據
15 print(sheet.row_values(0))#獲取第一行
16 for i in range(sheet.nrows):#0 1 2 3 4 5
17     print(sheet.row_values(i))#獲取第幾行的數據
18 
19 print(sheet.col_values(1))#取第一列的數據
20 for i in range(sheet.ncols):
21     print(sheet.col_values(i))#獲取第幾列的數據

三、對excel的修改操作:

將excel中的某個值修改並重新保存

from xlutils.copy import copy
import xlrd
#xlutils:修改excel
book1 = xlrd.open_workbook('stu.xls')
book2 = copy(book1)#拷貝一份原來的excel
# print(dir(book2))
sheet = book2.get_sheet(0)#獲取第幾個sheet頁,book2現在的是xlutils里的方法,不是xlrd的
sheet.write(1,3,0)
sheet.write(1,0,'hello')
book2.save('stu.xls')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM