學習Python的過程中,我們會遇到Excel的讀寫問題。這時,我們可以使用xlwt模塊將數據寫入Excel表格中,使用xlrd模塊從Excel中讀取數據。下面我們介紹如何實現使用Python對Excel進行讀寫操作。
Python版:3.5.2
通過pip安裝xlwt,xlrd這兩個模塊,如果沒有安裝的話:
pip install xlwt
pip install xlrd
一、對Excel文件進行寫入操作:
# -*- conding:utf-8 -*-__author__ = 'mayi'#How to write to an Excel using xlwt moduleimport xlwt#創建一個Wordbook對象,相當于創建了一個Excel文件book = xlwt.Workbook(encoding = "utf-8", style_compression = 0)#創建一個sheet對象,一個sheet對象對應Excel文件中的一張表格sheet = book.add_sheet("sheet1", cell_overwrite_ok = True)#向表sheet1中添加數據sheet.write(0, 0, "EnglishName") #其中,"0, 0"指定表中的單元格,"EnglishName"是向該單元格中寫入的內容sheet.write(1, 0, "MaYi")sheet.write(0, 1, "中文名字")sheet.write(1, 1, "螞蟻")#最后,將以上操作保存到指定的Excel文件中book.save("name.xls")
二、對Excel文件進行讀取操作:
# -*- conding:utf-8 -*-__author__ = 'mayi'# How to read from an Excel using xlrd moduleimport xlrd# 打開指定路徑中的xls文件,得到book對象xls_file = "name.xls"#打開指定文件book = xlrd.open_workbook(xls_file)# 通過sheet索引獲得sheet對象sheet1 = book.sheet_by_index(0)# # 獲得指定索引的sheet名# sheet1_name = book.sheet_names()[0]# print(sheet1_name)# # 通過sheet名字獲得sheet對象# sheet1 = book.sheet_by_name(sheet1_name)# 獲得行數和列數# 總行數nrows = sheet1.nrows#總列數ncols = sheet1.ncols# 遍歷打印表中的內容for i in range(nrows): for j in range(ncols): cell_value = sheet1.cell_value(i, j) print(cell_value, end = "/t") print("")
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林站長站!
新聞熱點
疑難解答