1. 程式人生 > >python中使用xlrd、xlwt操作excel表格詳解

python中使用xlrd、xlwt操作excel表格詳解

一、安裝xlrd模組和xlwt模組,兩種方法:

方法一:下載安裝包,解壓,然後使用python setup py install 安裝

  1. 下載xlrd模組和xlwt模組

    到python官網http://pypi.python.org/pypi/xlrd下載模組。下載的檔案例如:xlrd-0.9.3.tar.gz。

    到python官網http://pypi.python.org/pypi/xlwt下載模組。下載的檔案例如:xlwt-1.0.0.tar.gz

2. 安裝xlrd模組和xlwt模組

    a) 安裝前提是已經安裝python。

    b) 分別解壓下載的xlrd-0.9.3.tar.gz和xlwt-1.0.0.tar.gz到各自的目錄。

    c) cmd分別進入到上一步的解壓目錄, 分別執行python setup.py install完成安裝。

方法二:通過pip命令直接安裝即可           

       安裝庫:xlrd======================>  在控制檯執行命令:  pip install xlrd(xlrd,read,即使讀取的意思)

  安裝庫: xlwt ============================> 輸入 pip install xlwt 即可(write,即使寫入的意思)

二、使用xlrd模組讀取Excel檔案

#coding:utf-8
import xlrd
def read_excel():
    workbook=xlrd.open_workbook(r'E:\share\1532400376445.xls')
    print workbook.sheet_names() #獲取sheet的名稱
    mysheets=workbook.sheets() #獲取工作表
    '''三種獲取sheet的方法'''
    mysheet=mysheets[0] #通過索引順序取
    sheet1=workbook.sheet_by_index(0) #通過索引順序獲取
    # sheet1=workbook.sheet_by_name("世界盃")#通過名稱獲取
    '''獲取行數和列數'''
    nrows=sheet1.nrows
    ncols=sheet1.ncols
    print nrows
    print ncols
    '''獲取一行和一列'''
    rows=sheet1.row_values(3)#獲取第四行的內容
    cols=sheet1.col_values(2)#獲取第三行的內容
    print rows,cols
    '''讀取單元格資料'''

    print sheet1.cell(1,1)
    print sheet1.cell(2,3) #獲取資料型別+單元格資料
    mycell=sheet1.cell_value(1,2)  #直接獲取單元格資料
    print mycell

if __name__ == '__main__':
    read_excel()



三、使用xlwt模組寫入Excel檔案

#coding:utf-8
import xlrd
import xlwt
def write_excel():
    newexcel=xlwt.Workbook() #建立工作簿
    sheet1=newexcel.add_sheet('sheet1',cell_overwrite_ok=True)
    myStyle = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00')  # 資料格式
    '''寫入資料'''
    sheet1.write(0,0,'aaa',myStyle)
    sheet1.write(1,1,10,myStyle)
    '''儲存excel'''
    newexcel.save('aaa.xls')


if __name__ == '__main__':
    write_excel()

執行結果如下:

四.xlutils結合xlrd可以達到修改excel檔案目的

#coding:utf-8
import xlrd
import xlwt
from xlutils.copy import copy
def copy_excel_update():
    '''開啟excle'''
    workbook=xlrd.open_workbook(r'E:\share\1532400376445.xls')
    '''複製一份excel'''
    workbooknew=copy(workbook)
    '''獲取第一個sheet表格'''
    sheet=workbooknew.get_sheet(0)
    '''修改sheet表格裡面的內容'''
    sheet.write(0,0,'changed!')
    '''另存為一個表格'''
    workbooknew.save('newexcel.xls')
if __name__ == '__main__':
    copy_excel_update()

執行結果如下: