python筆記8,python筆記
前提:
python操作excel需要使用的模組有xlrd、xlwt、xlutils。對excel進行讀、寫、更新操作。操作excel時需要先匯入這些模組,demo如下:
excel-讀操作知識點:
1 import xlrd 2 ''' 3 讀取 excel的操作步驟如下: 4 1. 開啟excel,開啟的excel必須存在 5 2. 擷取sheet對象 6 3. 對excel進行操作: 7 擷取excel的總行數、總列數、讀取excel每一行的資料、讀取excel每一列的資料、擷取某個儲存格的值 8 ''' 9 #開啟excel,開啟的excel必須存在,返回book對象10 book = xlrd.open_workbook('students.xlsx')11 #通過索引擷取sheet對象12 sheet = book.sheet_by_index(0)13 #有多個sheet頁時可以通過sheet的名稱來擷取sheet對象14 sheet1 = book.sheet_by_name('Sheet1')15 16 #擷取excel的總行數,17 rows = sheet.nrows18 #擷取excel的總列數19 cols = sheet.ncols20 #擷取excel第2行的資料,返回結果為list:[2.0, 'b', 'women']21 row_value = sheet.row_values(2)22 #擷取excel第1列的資料,返回結果為list:['name', 'a', 'b', 'c', 'd', 'e', 'f', 'g', '小白', '小黑']23 col_values = sheet.col_values(1)24 #擷取儲存格第8行第1列的資料,返回結果為text: text:'小白'25 cell_value = sheet.cell(8, 1)26 #將text類型的結果轉換為str類型:小白27 cell_str = sheet.cell(8, 1).value
注意:擷取每行、每列、某個儲存格的值時,注意行、列的值要存在,否則會報錯:list index out of rangeexcel - 讀取excel小案例:
1 import xlrd 2 ''' 3 讀取excel的資料,讀取資料的列固定,迴圈讀取每行資料,讀取後的資料格式如下: 4 [ 5 {'name':xxx,'sex':xxx,'id':1}, 6 {'name':xxx,'sex':xxx,'id':1}, 7 ....... 8 ] 9 '''10 def readExcel():11 try:12 #若輸入的excel不存在,則開啟excel報錯13 book = xlrd.open_workbook('students.xlsx')14 except Exception as e:15 print('error msg:', e)16 else:17 sheet = book.sheet_by_index(0)18 #擷取excel的總行數19 rows = sheet.nrows20 stu_list = []21 #迴圈讀取每行資料,第0行是表頭資訊,所以從第1行讀取資料22 for row in range(1, rows):23 stu = {}24 #擷取第row行的第0列所有資料25 id = sheet.cell(row, 0).value26 name = sheet.cell(row, 1).value27 sex = sheet.cell(row, 2).value28 #將id、name、sex添加到字典,若元素不存在則新增,否則是更新操作29 stu['id'] = id30 stu['name'] = name31 stu['sex'] = sex32 stu_list.append(stu)33 print(stu_list)34 35 if __name__ == '__main__':36 readExcel()
excel資料格式如下:
excel - 寫操作知識點:
1 import xlwt 2 ''' 3 寫 excel的操作步驟如下: 4 1. 開啟excel,開啟不存在的excel,若開啟已存在的excel,進行寫操作,寫入的資料會覆蓋以前的資料 5 2. 擷取sheet對象並指定sheet的名稱 6 3. 對excel進行操作: 7 寫入excel、儲存excel 8 ''' 9 #開啟excel建立book對象10 book = xlwt.Workbook()11 #建立sheet指定sheet名稱12 sheet = book.add_sheet('stu2')13 #寫入excel資料,第n行第n列寫入某個值,寫入的資料類型為str14 sheet.write(0, 0, '編號')15 sheet.write(0, 1, '姓名')16 sheet.write(0, 2, '年齡')17 #儲存excel,儲存的尾碼必須是xls18 book.save('studet.xls')
excel寫入 新的excel後,資料格式如下:
excel操作 已存在的excel,進行寫操作後的 excel格式如下:
---->
excel - 寫excel小案例:
1 import xlwt 2 ''' 3 將list資料: 4 [{'name': '小白', 'id': 1.0, 'sex': '男'}, 5 {'name': '小花', 'id': 2.0, 'sex': '女'}, 6 {'name': '小黑', 'id': 3.0, 'sex': '男'}, 7 {'name': '小茹', 'id': 4.0, 'sex': '女'}, 8 {'name': '小小', 'id': 5.0, 'sex': '男'}] 9 寫入excel,title資訊為:編號、姓名、性別10 '''11 def writeExcel():12 book = xlwt.Workbook()13 sheet = book.add_sheet('stu')14 titles = ['編號', '姓名', '性別']15 #迴圈讀取titles的長度,col的值為:0,1,2,並將title值寫入excel16 for title_col in range(len(titles)):17 #title 寫入excel的第0行的第col列,寫入titles[col]值18 sheet.write(0, title_col, titles[title_col])19 students_list = [{'name': '小白', 'id': 1.0, 'sex': '男'},{'name': '小花', 'id': 2.0, 'sex': '女'},{'name': '小黑', 'id': 3.0, 'sex': '男'},{'name': '小茹', 'id': 4.0, 'sex': '女'},{'name': '小小', 'id': 5.0, 'sex': '男'}]20 for stu_row in range(len(students_list)):21 #迴圈讀取student_list的長度,從0開始,寫入excel時從第1行開始寫入資料22 #寫入excel的資料是從list裡進行取值,擷取list的每個元素,返回字典,然後通過字典的key擷取value23 sheet.write(stu_row+1, 0, students_list[stu_row]['id'])24 sheet.write(stu_row+1, 1, students_list[stu_row]['name'])25 sheet.write(stu_row+1, 2, students_list[stu_row]['sex'])26 book.save('student.xls')27 if __name__ == '__main__':28 writeExcel()
excel資料格式如下:
excel- 更新操作知識點:
1 import xlrd 2 from xlutils.copy import copy 3 ''' 4 更新excel操作: 5 1. 開啟excel,更新的excel必須存在 6 2. 複製一個新的excel,使用xlutils模組中的copy方法 7 3. 更新excel內的資料 8 4. 儲存更新後的excel資料,以前的excel資料不會更改 9 '''10 from xlutils.copy import copy11 #開啟excel12 book = xlrd.open_workbook('student.xlsx')13 #複製一個新的excel14 new_book = copy(book)15 #查看某個對象下的所有方法16 #print(dir(new_book))17 #擷取新excel的sheet對象18 sheet = new_book.get_sheet(0)19 #新增一列資料20 sheet.write(0, 3, '更新')21 #更新第4行第1列的值,將其修改為'郭靜',修改的資料類型為str22 sheet.write(4, 1, '郭靜')23 #儲存更改後的excel,以前的excel資料不更改24 new_book.save('student.xls')
以上為excel簡單操作~~~~