python之excel讀寫操作
阿新 • • 發佈:2018-07-23
install excel讀寫 下載 int sheet 指定路徑 file 列數 裝包
一、xlrd和xlwt安裝
1、下載xlwt安裝包https://pypi.org/project/xlwt/#files
2、解壓後進入文件目錄
3、執行python setup.py install
二、讀取操作
1 # -*- conding:utf-8 -*- 2 __author__ = ‘dsh‘ 3 # How to read from an Excel using xlrd module 4 import xlrd 5 # 關聯指定路徑中的xls文件,得到book對象 6 file_name = "name.xls" 7 #打開指定文件,創建文件對象 8 book = xlrd.open_workbook(file_name)9 # 通過sheet索引獲得sheet對象 10 sheet1 = book.sheet_by_index(0) 11 # # 獲得指定索引的sheet名 12 # sheet1_name = book.sheet_names()[0] 13 # print(sheet1_name) 14 # # 通過sheet名字獲得sheet對象 15 # sheet1 = book.sheet_by_name(sheet1_name) 16 # 獲得行數和列數 17 # 總行數 18 nrows = sheet1.nrows 19 #總列數 20 ncols = sheet1.ncols 21 # 遍歷打印表中的內容22 for i in range(nrows): 23 for j in range(ncols): 24 cell_value = sheet1.cell_value(i, j) 25 print(cell_value, end = "\t") 26 print("")
三、寫入操作
1 # -*- conding:utf-8 -*- 2 __author__ = ‘dsh‘ 3 #How to write to an Excel using xlwt module 4 import xlwt 5 #創建一個Wordbook對象,相當於創建了一個Excel文件6 book = xlwt.Workbook(encoding = "utf-8", style_compression = 0) 7 #創建一個sheet對象,一個sheet對象對應Excel文件中的一張表格 8 sheet = book.add_sheet("sheet1", cell_overwrite_ok = True) 9 #向表sheet1中添加數據 10 sheet.write(0, 0, "EnglishName") #其中,"0, 0"指定表中的單元格,"EnglishName"是向該單元格中寫入的內容 11 sheet.write(1, 0, "MaYi") 12 sheet.write(0, 1, "中文名字") 13 sheet.write(1, 1, "螞蟻") 14 #最後,將以上操作保存到指定的Excel文件中 15 book.save("name.xls")
四、實名制文檔格式轉換讀寫案例
#!/usr/bin/python # -*- coding: utf-8 -*- import xlrd import xlwt import sys import os __author__ = ‘dsh‘ file_name = "1111.xls" book_read = xlrd.open_workbook(file_name) sheet_read = book_read.sheet_by_index(0) nrows_read = sheet_read.nrows ncols_read = sheet_read.ncols book_write = xlwt.Workbook(encoding = "utf-8",style_compression = 0) sheet_write = book_write.add_sheet("sheet1",cell_overwrite_ok = True) #把第0列寫到第1列 for i in range(nrows_read): cell_value = sheet_read.cell_value(i,0) sheet_write.write(i,1,cell_value) #把第10列數據寫到第3列 for i in range(nrows_read): cell_value = sheet_read.cell_value(i,10) sheet_write.write(i,3,cell_value) book_write.save("2222.xls")
python之excel讀寫操作