欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Python對Excel進行讀寫操作

 更新時間:2017年03月30日 17:26:12   作者:騎著螞蟻流浪  
學習Python的過程中,我們會遇到Excel的讀寫問題。這時,我們可以使用xlwt模塊將數(shù)據(jù)寫入Excel表格中,使用xlrd模塊從Excel中讀取數(shù)據(jù)。下面我們介紹如何實現(xiàn)使用Python對Excel進行讀寫操作。

學習Python的過程中,我們會遇到Excel的讀寫問題。這時,我們可以使用xlwt模塊將數(shù)據(jù)寫入Excel表格中,使用xlrd模塊從Excel中讀取數(shù)據(jù)。下面我們介紹如何實現(xiàn)使用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 module
import xlwt
#創(chuàng)建一個Wordbook對象,相當于創(chuàng)建了一個Excel文件
book = xlwt.Workbook(encoding = "utf-8", style_compression = 0)
#創(chuàng)建一個sheet對象,一個sheet對象對應Excel文件中的一張表格
sheet = book.add_sheet("sheet1", cell_overwrite_ok = True)
#向表sheet1中添加數(shù)據(jù)
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 module
import 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)
# 獲得行數(shù)和列數(shù)
# 總行數(shù)
nrows = sheet1.nrows
#總列數(shù)
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("")

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關文章

最新評論