python操作excel文檔

我的環境是 win 7  64位 +  pyCharm + pip + python3.6

需要下載2個包:xlwt 和 xlrd

地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#xlwt

           https://www.lfd.uci.edu/~gohlke/pythonlibs/#xlrd

準備一個文檔,這裏命名爲: read.xls

進行讀操作:

import xlrd  # 用於讀取excel
import xlwt  # 用於寫入excel

file = xlrd.open_workbook(r'read.xlsx') # 打開文件
table = file.sheets()[0] # 打開第一張表
nrows = table.nrows      # 獲取表的行數
for i in range(nrows):
    print( table.row_values(i)[:6:1] ) # 輸出第i 行前6 列,步長爲1

進行寫操作:

import xlrd  # 用於讀取excel
import xlwt  # 用於寫入excel

file = xlwt.Workbook() # 創建工作簿
sheet1 = file.add_sheet(u'sheet1', cell_overwrite_ok=True) # 創建sheet
# 數據
data = [['', '第一列', '第二列', '第三列', '第四列', '第五列'],
        ['第一行', 5, 4, 3, 2, 1],
        ['第二行', 10, 9, 8, 7, 6],
        ['第三行', 15, 14, 13, 12, 11],
        ['第四行', 20, 19, 18, 17, 16],
        ['第五行', 25, 24, 23, 22, 21]]
# 寫入數據
i = 0
for it in data:
    for j in range(6):
        sheet1.write(i, j, it[j]) # 依次寫入每行數據
    i += 1
# 保存文件
file.save('write.xls')

寫入Excel結果圖:

也可以使用pandas構造DataFrame,調用to_excel方法實現Excel的數據寫入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章