用python對excel進(jìn)行操作(讀,寫,修改)
將一個(gè)列表的數(shù)據(jù)寫入excel, 第一行是標(biāo)題,下面行數(shù)具體的數(shù)據(jù)
import xlwt#只能寫不能讀stus = [[’姓名’, ’年齡’, ’性別’, ’分?jǐn)?shù)’], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9] ]book = xlwt.Workbook()#新建一個(gè)excelsheet = book.add_sheet(’case1_sheet’)#添加一個(gè)sheet頁row = 0#控制行for stu in stus: col = 0#控制列 for s in stu:#再循環(huán)里面list的值,每一列 sheet.write(row,col,s) col+=1 row+=1book.save(’stu_1.xls’)#保存到當(dāng)前目錄下二、對excel 的讀操作:
import xlrd#只能讀不能寫book = xlrd.open_workbook(’stu.xls’)#打開一個(gè)excelsheet = book.sheet_by_index(0)#根據(jù)順序獲取sheetsheet2 = book.sheet_by_name(’case1_sheet’)#根據(jù)sheet頁名字獲取sheetprint(sheet.cell(0,0).value)#指定行和列獲取數(shù)據(jù)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)#獲取每一行的數(shù)據(jù)print(sheet.row_values(0))#獲取第一行for i in range(sheet.nrows):#0 1 2 3 4 5 print(sheet.row_values(i))#獲取第幾行的數(shù)據(jù)print(sheet.col_values(1))#取第一列的數(shù)據(jù)for i in range(sheet.ncols): print(sheet.col_values(i))#獲取第幾列的數(shù)據(jù)三、對excel的修改操作:
將excel中的某個(gè)值修改并重新保存
from xlutils.copy import copyimport xlrd#xlutils:修改excelbook1 = xlrd.open_workbook(’stu.xls’)book2 = copy(book1)#拷貝一份原來的excel# print(dir(book2))sheet = book2.get_sheet(0)#獲取第幾個(gè)sheet頁,book2現(xiàn)在的是xlutils里的方法,不是xlrd的sheet.write(1,3,0)sheet.write(1,0,’hello’)book2.save(’stu.xls’)
以上就是用python對excel進(jìn)行操作(讀,寫,修改)的詳細(xì)內(nèi)容,更多關(guān)于python對excel進(jìn)行操作的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python編寫memcached啟動(dòng)腳本代碼實(shí)例2. 詳解Python利用configparser對配置文件進(jìn)行讀寫操作3. Python編寫單元測試代碼實(shí)例4. python編寫實(shí)現(xiàn)抽獎(jiǎng)器5. python 編寫輸出到csv的操作6. Python編寫萬花尺圖案實(shí)例7. python字典通過值反查鍵的實(shí)現(xiàn)(簡潔寫法)8. python+flask編寫一個(gè)簡單的登錄接口9. 用Python編寫腳本使IE實(shí)現(xiàn)代理上網(wǎng)的教程10. 使用python svm實(shí)現(xiàn)直接可用的手寫數(shù)字識別
