Python模組安裝與讀取Excel

2021-06-22 12:41:29 字數 3126 閱讀 4404

今天,想用python讀取一下excel中的資料,從網上查詢了乙個例子,是要安裝相關的模組:

模組安裝,前提是已經安裝了python 環境。

下好之後,把

xlrd-0.9.3.tar.gz

解壓後 ,把

xlrd

目錄 直接拷貝到 python安裝目錄下的 lib/site-packages/ 下,即可

或者 執行cmd安裝:

和手工解壓的也一樣,會把xlrd複製到c:\python27\lib\site-packages下:

讀取excel資料的**

#!/usr/bin/python

#-*- encoding: utf-8 -*-

'''created on 2023年6月19日

@author: administrator

'''

import  xdrlib ,sys

import xlrd

def open_excel(file= 'c:/2255888.xls'):

try:

data = xlrd.open_workbook(file)

return data

except exception,e:

print str(e)

#根據索引獲取excel**中的資料   引數:file:excel檔案路徑     colnameindex:表頭列名所在行的所以  ,by_index:表的索引

def excel_table_byindex(file= 'c:/2255888.xls',colnameindex=0,by_index=0):

data = open_excel(file)

table = data.sheets()[by_index]

nrows = table.nrows #行數

ncols = table.ncols #列數

colnames =  table.row_values(colnameindex) #某一行資料 

list =

for rownum in range(1,nrows):

row = table.row_values(rownum)

if row:

for i in range(len(colnames)):

return list

#根據名稱獲取excel**中的資料   引數:file:excel檔案路徑     colnameindex:表頭列名所在行的所以  ,by_name:sheet1名稱

def excel_table_byname(file= 'c:/2255888.xls',colnameindex=0,by_name=u'sheet1'):

data = open_excel(file)

table = data.sheet_by_name(by_name)

nrows = table.nrows #行數 

colnames =  table.row_values(colnameindex) #某一行資料 

list =

for rownum in range(1,nrows):

row = table.row_values(rownum)

if row:

for i in range(len(colnames)):

return list

def main():

tables = excel_table_byindex()

for row in tables:

print row

tables = excel_table_byname()

for row in tables:

print row

if __name__=="__main__":

main()

結果如下:這個結果是讀取到excel了,但還是要優化一下資料

從網上查詢到的一些使用技巧

獲取乙個工作表

table = data.sheets()[0]          #通過索引順序獲取

table = data.sheet_by_index(0) #通過索引順序獲取

table = data.sheet_by_name(u'sheet1')#通過名稱獲取

獲取整行和整列的值(陣列)

table.row_values(i)

table.col_values(i)

獲取行數和列數

nrows = table.nrows

ncols = table.ncols

迴圈行列表資料

for i in range(nrows ):

print table.row_values(i)

單元格

cell_a1 = table.cell(0,0).value

cell_c4 = table.cell(2,3).value

使用行列索引

cell_a1 = table.row(0)[0].value

cell_a2 = table.col(1)[0].value

簡單的寫入

row = 0

col = 0

# 型別 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

ctype = 1

value = '單元格的值'

xf = 0 # 擴充套件的格式化 

table.put_cell(row, col, ctype, value, xf)

table.cell(0,0)  #單元格的值

table.cell(0,0).value #單元格的值'

利用xlrd模組實現Python讀取Excel文件

coding cp936 python讀取excel import xlrd defmain xls xlrd.open workbook d 11.xls try mysheet xls.sheet by name sheet1 找到名為sheet1的工作表。區分大小寫 except print ...

Python使用openpyxl讀取Excel資訊

python的用途越來越廣,不能不開始學習使用了,今天寫個練手的demo,最大的感覺是python和es6挺像的。主要功能是彈出對話方塊,選擇本地excel檔案,然後迴圈讀取出來。使用的是openpyxl模組,只支援xlsx,不支援xls。如下 import openpyxl import tkin...

Python 模組發布與安裝

安裝模組 在模組所在資料夾下新建 setup.py 檔案如下 from distutils.core import setup setup name 檔名 version 版本號 description 模組說明 author 作者 py modules 模組py檔案1 模組py檔案2 python...