日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python把数据写入excel_Python读取和写入Excel文件(转)

發布時間:2024/9/27 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python把数据写入excel_Python读取和写入Excel文件(转) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

學習用Python處理Excel文件,這里主要用xlrd和xlwt模塊,用前需要安裝!本文是來自幾篇博客和官網tutorial的整理,主要是一個入門。更多的處理Excel的方法請到官網學習,鏈接為:http://www.simplistix.co.uk/presentations/python-excel.pdf

另外,幾篇博客的參考資料:

http://syue.com/Software/Language/Python/21655.html

http://blog.csdn.net/wangxiaoyan1988/article/details/6562374

http://www.2cto.com/kf/201207/140006.html

安裝xlrd模塊:到python官網下載http://pypi.python.org/pypi/xlrd模塊安裝,前提是已經安裝了python 環境。

解壓后,打開cmd切換到對應目錄,去執行:D:\dev_tools\python\excel\xlrd-1.0.0>setup.py install

安裝成功!

安裝xlutils模塊: http://pypi.python.org/pypi/xlutils 去下載最新版本的,解壓后,打開cmd切換到對應目錄,去執行:D:\dev_tools\python\excel\xlutils-2.0.0>setup.py install,安裝完成。

A:Excel數據的類型及組織方式

每一個Excel數據文件從上至下分為三個層級的對象:

workbook: 每一個Excel文件就是一個workbook。

sheet: 每一個workbook中可以包含多個sheet,具體就對應Excel中我們在左下腳所看到的“sheet1”,“sheet2”等。

cell: 每一個sheet就是我們通常所看到的一個表格,可以含有m行,n列,每個確定的行號,列號所對應的一個格子就是一個cell。

B: 從Excel中讀取數據

從一個既有的xlsx文件中讀取數據,按照Excel文件的三個層級,分別做以下三個步驟

1. 打開workbook:

import xlrd

book = xlrd.open_workbook("myfile.xls") #book就賦值為一個Excel文件了

注:

Book 類的方法、屬性等:即就可以對上面的book進行操作了

book.nsheets: 在Book對象中的文件有多少個worksheet

book.sheet_by_index(sheetx): 根據提供的sheetx索引來獲取我們需要的sheet表,返回的是一個Sheet類的實例。

book.sheet_by_name(sheet_name): 根據提供的sheet_name來獲取對應名稱的sheet類對象,返回的也是一個Sheet類的對象

book.sheet_names(): 在Book對象中的所有sheet表的名稱列表

book.sheets(): 返回在Book對象中所有的Sheet對象實例列表

2. 打開所需的sheet:

sh = book.sheet_by_index(0) #獲得一個sheet,也可以使名字獲得

print sh.name, sh.nrows, sh.ncols

注:

Sheet類方法、屬性等:

sh.cell(rowx, colx): 根據給出的行和列的參數獲取得到cell類,返回一個Cell類實例對象

sh.cell_type(rowx, colx): 返回對應的cell對象的Type類型

sh.cell_value(rowx, colx): 返回對應的cell對象的value值

sh.col(colx): 返回指定列的所有cell類對象序列

sh.name: 返回sheet對象的名稱

sh.ncols: 返回在sheet對象中的列的數目

sh.nrows: 返回在sheet對象中的行的數目

sh.row(rowx): 返回指定的行的所有cell對象的序列

3. 獲取對應cell的值:

cell=sh.cell(rowx=29, colx=3) #根據給出的行和列的參數獲取得到cell類,返回一個Cell類實例對象

sh.cell_value(rowx=29, colx=3)

Cell類的屬性、方法如下:

Cell類對象有3種屬性:ctype, value, xf_index

如果在excel文件打開的時候,formatting_info未啟用的時候,xf_index是為None

下面列出了cell的類型,以及他們在python中所代表的值

type symbol type number python value

XL_CELL_EMPTY 0 空的字符串''

XL_CELL_TEXT 1 unicode字符串

XL_CELL_NUMBER 2 float

XL_CELL_DATE 3 float

XL_CELL_BOOLEAN 4 int;1 --- True,0 --- False

XL_CELL_ERROR 5 int代表是一個excel內部錯誤碼;

XL_CELL_BLANK 6 空的字符串'', 注意:這個類型僅僅會出現,當函數open_workbook(..,formatting_info=True)這樣設置的時候

4.一個讀取Excel的例子

import xlrd

book = xlrd.open_workbook("myfile.xls")

print "The number of worksheets is", book.nsheets

print "Worksheet name(s):", book.sheet_names()

sh = book.sheet_by_index(0)

print sh.name, sh.nrows, sh.ncols

print "Cell D30 is", sh.cell_value(rowx=29, colx=3)

for rx in range(sh.nrows):

print sh.row(rx)

C: Writing Excel Files

All the examples shown below can be found in the xlwt directory of the course material.讀Excel xlrd模塊,寫用xlwt模塊

1. Creating elements within a Workbook創建一個Excel文件

Import xlwt

wb=xlwt.Workbook(“zc.xls”) #Workbook 首字母大寫

2. Worksheets 添加Sheet

Worksheets are created with the add_sheet method of the Workbook class.

To retrieve an existing sheet from a Workbook, use its get_sheet method. This method is particularly useful when the Workbook has been instantiated by xlutils.copy.

Sheet1=wb.add_sheet(“sheetname”)

3. Rows and Columns 行與列的表示:

row1 = sheet1.row(1)

col0=sheet2.col(0)

4. Cells

Cells can be written using either the write method of either the Worksheet or Row class.

sheet1.write(0,1,'B1')

row1.write(0,'A2')

5. svave 保存文件:

wb.save(“zc.xls”)

6. Excel寫入的一個簡單的例子

from xlwt import Workbook

book = Workbook()

sheet1 = book.add_sheet('Sheet 1') #添加一個sheet

book.add_sheet('Sheet 2')

sheet1.write(0,0,'A1') #通過sheet添加cell值

sheet1.write(0,1,'B1')

row1 = sheet1.row(1)

row1.write(0,'A2') #還可以通過row屬性添加cell值

row1.write(1,'B2')

sheet1.col(0).width = 10000

sheet2 = book.get_sheet(1)

sheet2.row(0).write(0,'Sheet 2 A1') #又一種添加

sheet2.row(0).write(1,'Sheet 2 B1')

sheet2.flush_row_data()

sheet2.write(1,0,'Sheet 2 A3')

sheet2.col(0).width = 5000

sheet2.col(0).hidden = True

book.save('simple.xls')

D: 稍微復雜的例子和鞏固

Ex1:

import xlrd

fname = "sample.xls" #一個文件路徑和文件名

bk = xlrd.open_workbook(fname) #打開一個workbook

shxrange = range(bk.nsheets) #各個sheet之間的轉換?

try: #提取sheet1?

sh = bk.sheet_by_name("Sheet1")

except:

print "no sheet in %s named Sheet1" % fname

return None

nrows = sh.nrows

ncols = sh.ncols

print "nrows %d, ncols %d" % (nrows, ncols)

cell_value = sh.cell_value(1,1)

print cell_value

row_list = []

for i in range(1, nrows):

row_data = sh.row_values(i)

row_list.append(row_data)

ex2:

1

2 import xlrd

3 import xlwt

4

5 class OperExcel():

6 #讀取Excel表

7 def rExcel(self,inEfile,outfile):

8 rfile = xlrd.open_workbook(inEfile)

9 #創建索引順序獲取一個工作表

10 table = rfile.sheet_by_index(0)

11 #其他方式

12 #table = rfile.sheets()[0]

13 #table = rfile.sheet_by_name(u'Sheet1')

14

15 #獲取整行,整列的值

16 table.row_values(0)

17 table.col_values(0)

18

19 #獲取行數和列數

20 nrows = table.nrows - 1

21 ncols = table.ncols

22

23 #循環獲取列表的數據

24 #for i in range(nrows):

25 # print table.row_values(i)

26 wfile = open(outfile,'w')

27 #獲取第一列中的所有值

28 for i in range(nrows):

29 #table.cell(i,0).value獲取某一單元格的值

30 wfile.write(table.cell(i,0).value.encode('utf8') + '\n')

31 wfile.close()

32

33 #將數據寫入Excel表

34 def wExcel(self,infile,outEfile):

35 rfile = open(infile,'r')

36 buf = rfile.read().split('\n')

37 rfile.close()

38

39 w = xlwt.Workbook()

40 sheet = w.add_sheet('sheet1')

41 for i in range(len(buf)):

42 print buf[i]

43 sheet.write(i,0,buf[i].decode('utf8'))

44 w.save(outEfile)

45

46 if __name__ == '__main__':

47 t = OperExcel()

48 t.rExcel('test.xls','test')

49 t.wExcel('test','1.xls')

50 # 作者:sunrise

總結

以上是生活随笔為你收集整理的python把数据写入excel_Python读取和写入Excel文件(转)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。