用python對excel進行操作(讀,寫,修改)
將一個列表的數據寫入excel, 第一行是標題,下面行數具體的數據
import xlwt#只能寫不能讀stus = [[’姓名’, ’年齡’, ’性別’, ’分數’], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9], [’mary’, 20, ’女’, 89.9] ]book = xlwt.Workbook()#新建一個excelsheet = 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+=1book.save(’stu_1.xls’)#保存到當前目錄下二、對excel 的讀操作:
import xlrd#只能讀不能寫book = xlrd.open_workbook(’stu.xls’)#打開一個excelsheet = book.sheet_by_index(0)#根據順序獲取sheetsheet2 = book.sheet_by_name(’case1_sheet’)#根據sheet頁名字獲取sheetprint(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))#獲取第幾列的數據三、對excel的修改操作:
將excel中的某個值修改并重新保存
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)#獲取第幾個sheet頁,book2現在的是xlutils里的方法,不是xlrd的sheet.write(1,3,0)sheet.write(1,0,’hello’)book2.save(’stu.xls’)
以上就是用python對excel進行操作(讀,寫,修改)的詳細內容,更多關于python對excel進行操作的資料請關注好吧啦網其它相關文章!
相關文章: