1. 程式人生 > >Python—對Excel進行讀寫操作

Python—對Excel進行讀寫操作

href ace 需要 文件中 tle net 過程 ova 設置

學習Python的過程中,我們會遇到Excel的讀寫問題。通過搜索得知,我們可以使用xlwt module將數據寫入Excel表格,使用xlrd module從Excel讀取數據。下面介紹如何實現使用python對Excel進行讀寫操作。

(1)對Excel的寫操作:

# -*- coding: utf-8 -*-
#導入xlwt模塊
import xlwt
# 創建一個Workbook對象,這就相當於創建了一個Excel文件
book = xlwt.Workbook(encoding=‘utf-8‘, style_compression=0)
‘‘‘
Workbook類初始化時有encoding和style_compression參數
encoding:設置字符編碼,一般要這樣設置:w = Workbook(encoding=‘utf-8‘),就可以在excel中輸出中文了。
默認是ascii。當然要記得在文件頭部添加:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
style_compression:表示是否壓縮,不常用。
‘‘‘
#創建一個sheet對象,一個sheet對象對應Excel文件中的一張表格。
# 在電腦桌面右鍵新建一個Excel文件,其中就包含sheet1,sheet2,sheet3三張表
sheet = book.add_sheet(‘test‘, cell_overwrite_ok=True)
# 其中的test是這張表的名字,cell_overwrite_ok,表示是否可以覆蓋單元格,其實是Worksheet實例化的一個參數,默認值是False
# 向表test中添加數據
sheet.write(0, 0, ‘EnglishName‘)  # 其中的‘0-行, 0-列‘指定表中的單元,‘EnglishName‘是向該單元寫入的內容
sheet.write(1, 0, ‘Marcovaldo‘)
txt1 = ‘中文名字‘
sheet.write(0, 1, txt1.decode(‘utf-8‘))  # 此處需要將中文字符串解碼成unicode碼,否則會報錯
txt2 = ‘馬可瓦多‘
sheet.write(1, 1, txt2.decode(‘utf-8‘))

# 最後,將以上操作保存到指定的Excel文件中
book.save(r‘e:\test1.xls‘)  # 在字符串前加r,聲明為raw字符串,這樣就不會處理其中的轉義了。否則,可能會報錯

  完成後在電腦的E盤下邊會產生test1.xls文件,入下圖:

技術分享

(2)對Excel的寫操作

  1、表格的內容如下:

   技術分享

  2、

# -*- coding: utf-8 -*-
import xlrd
xlsfile = r"C:\Users\Administrator\Desktop\test\Account.xls"# 打開指定路徑中的xls文件
book = xlrd.open_workbook(xlsfile)#得到Excel文件的book對象,實例化對象
sheet0 = book.sheet_by_index(0) # 通過sheet索引獲得sheet對象
print "1、",sheet0
sheet_name = book.sheet_names()[0]# 獲得指定索引的sheet表名字
print "2、",sheet_name
sheet1 = book.sheet_by_name(sheet_name)# 通過sheet名字來獲取,當然如果知道sheet名字就可以直接指定
nrows = sheet0.nrows    # 獲取行總數
print "3、",nrows
#循環打印每一行的內容
for i in range(nrows):
    print sheet1.row_values(i)
ncols = sheet0.ncols    #獲取列總數
print "4、",ncols
row_data = sheet0.row_values(0)     # 獲得第1行的數據列表
print row_data
col_data = sheet0.col_values(0)     # 獲得第1列的數據列表
print "5、",col_data
# 通過坐標讀取表格中的數據
cell_value1 = sheet0.cell_value(0, 0)
print "6、",cell_value1
cell_value2 = sheet0.cell_value(0, 1)
print "7、",cell_value2

  3、執行的結果:

技術分享

參考資料:

http://blog.csdn.net/majordong100/article/details/50708365

http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html

http://www.cnblogs.com/snake-hand/p/3153158.html

Python—對Excel進行讀寫操作