最新文章專題視頻專題問(wèn)答1問(wèn)答10問(wèn)答100問(wèn)答1000問(wèn)答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問(wèn)答文章1 問(wèn)答文章501 問(wèn)答文章1001 問(wèn)答文章1501 問(wèn)答文章2001 問(wèn)答文章2501 問(wèn)答文章3001 問(wèn)答文章3501 問(wèn)答文章4001 問(wèn)答文章4501 問(wèn)答文章5001 問(wèn)答文章5501 問(wèn)答文章6001 問(wèn)答文章6501 問(wèn)答文章7001 問(wèn)答文章7501 問(wèn)答文章8001 問(wèn)答文章8501 問(wèn)答文章9001 問(wèn)答文章9501
當(dāng)前位置: 首頁(yè) - 科技 - 知識(shí)百科 - 正文

用python讀寫excel的方法

來(lái)源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 14:40:35
文檔

用python讀寫excel的方法

用python讀寫excel的方法:本文實(shí)例講述了用python讀寫excel的方法。分享給大家供大家參考。具體如下: 最近需要從多個(gè)excel表里面用各種方式整理一些數(shù)據(jù),雖然說(shuō)原來(lái)用過(guò)java做這類事情,但是由于最近在學(xué)python,所以當(dāng)然就決定用python嘗試一下了。發(fā)現(xiàn)python果然簡(jiǎn)潔很多。
推薦度:
導(dǎo)讀用python讀寫excel的方法:本文實(shí)例講述了用python讀寫excel的方法。分享給大家供大家參考。具體如下: 最近需要從多個(gè)excel表里面用各種方式整理一些數(shù)據(jù),雖然說(shuō)原來(lái)用過(guò)java做這類事情,但是由于最近在學(xué)python,所以當(dāng)然就決定用python嘗試一下了。發(fā)現(xiàn)python果然簡(jiǎn)潔很多。

本文實(shí)例講述了用python讀寫excel的方法。分享給大家供大家參考。具體如下:

最近需要從多個(gè)excel表里面用各種方式整理一些數(shù)據(jù),雖然說(shuō)原來(lái)用過(guò)java做這類事情,但是由于最近在學(xué)python,所以當(dāng)然就決定用python嘗試一下了。發(fā)現(xiàn)python果然簡(jiǎn)潔很多。這里簡(jiǎn)單記錄一下。(由于是用到什么學(xué)什么,所以不算太深入,高手勿噴,歡迎指導(dǎo))

一、讀excel表

讀excel要用到xlrd模塊,官網(wǎng)安裝(http://pypi.python.org/pypi/xlrd)。然后就可以跟著里面的例子稍微試一下就知道怎么用了。大概的流程是這樣的:

1、導(dǎo)入模塊

代碼如下:

import xlrd

2、打開(kāi)Excel文件讀取數(shù)據(jù)

代碼如下:

data = xlrd.open_workbook('excel.xls')

3、獲取一個(gè)工作表

① table = data.sheets()[0] #通過(guò)索引順序獲取
② table = data.sheet_by_index(0) #通過(guò)索引順序獲取
③ table = data.sheet_by_name(u'Sheet1')#通過(guò)名稱獲取
4、獲取整行和整列的值(返回?cái)?shù)組)

代碼如下:

table.row_values(i)
table.col_values(i)


5、獲取行數(shù)和列數(shù) 

代碼如下:

table.nrows
table.ncols


6、獲取單元格

代碼如下:

table.cell(0,0).value
table.cell(2,3).value


就我自己使用的時(shí)候覺(jué)得還是獲取cell最有用,這就相當(dāng)于是給了你一個(gè)二維數(shù)組,余下你就可以想怎么干就怎么干了。得益于這個(gè)十分好用的庫(kù)代碼很是簡(jiǎn)潔。但是還是有若干坑的存在導(dǎo)致話了一定時(shí)間探索。現(xiàn)在列出來(lái)供后人參考吧:

1、首先就是我的統(tǒng)計(jì)是根據(jù)姓名統(tǒng)計(jì)各個(gè)表中的信息的,但是調(diào)試發(fā)現(xiàn)不同的表中各個(gè)名字貌似不能夠匹配,開(kāi)始懷疑過(guò)編碼問(wèn)題,不過(guò)后來(lái)發(fā)現(xiàn)是因?yàn)椤 】崭?。因?yàn)樵趀xcel中輸入的時(shí)候很可能會(huì)順手在一些名字后面加上幾個(gè)空格或是tab鍵,這樣看起來(lái)沒(méi)什么差別,但是程序處理的時(shí)候這就是兩個(gè)完全  不同的串了。我的解決方法是給每個(gè)獲取的字符串都加上strip()處理一下。效果良好

2、還是字符串的匹配,在判斷某個(gè)單元格中的字符串(中文)是否等于我所給出的的時(shí)候發(fā)現(xiàn)無(wú)法匹配,并且各種unicode也不太奏效,百度過(guò)一些解決  方案,但是都比較復(fù)雜或是沒(méi)用。最后我采用了一個(gè)比較變通的方式:直接從excel中獲取我想要的值再進(jìn)行比較,效果是不錯(cuò)就是通用行不太好,個(gè)  呢不能問(wèn)題還沒(méi)解決。
二、寫excel表

寫excel表要用到xlwt模塊,官網(wǎng)下載(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:

1、導(dǎo)入模塊

代碼如下:

import xlwt


2、創(chuàng)建workbook(其實(shí)就是excel,后來(lái)保存一下就行)

代碼如下:

workbook = xlwt.Workbook(encoding = 'ascii')


3、創(chuàng)建表

代碼如下:

worksheet = workbook.add_sheet('My Worksheet')


4、往單元格內(nèi)寫入內(nèi)容

代碼如下:

worksheet.write(0, 0, label = 'Row 0, Column 0 Value')


5、保存

代碼如下:

workbook.save('Excel_Workbook.xls')


由于我的需求比較簡(jiǎn)單,所以這上面沒(méi)遇到什么問(wèn)題,唯一的就是建議還是用ascii編碼,不然可能會(huì)有一些詭異的現(xiàn)象。

當(dāng)然xlwt功能遠(yuǎn)遠(yuǎn)不止這些,他甚至可以設(shè)置各種樣式之類的。附上一點(diǎn)例子

代碼如下:


Examples Generating Excel Documents Using Python's xlwt

Here are some simple examples using Python's xlwt library to dynamically generate Excel documents.

Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:http://packages.python.org/ezodf/index.html

The Simplest Example
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
workbook.save('Excel_Workbook.xls')

Formatting the Contents of a Cell
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
font = xlwt.Font() # Create the Font
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # Create the Style
style.font = font # Apply the Font to the Style
worksheet.write(0, 0, label = 'Unformatted value')
worksheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
workbook.save('Excel_Workbook.xls')

Attributes of the Font Object
font.bold = True # May be: True, False
font.italic = True # May be: True, False
font.struck_out = True # May be: True, False
font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC
font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT
font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE
font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I
font.colour_index = ?
font.get_biff_record = ?
font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height.
font.name = ?
font.outline = ?
font.shadow = ?

Setting the Width of a Cell
import xltw
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 'My Cell Contents')
worksheet.col(0).width = 3333 # 3333 = 1" (one inch).
workbook.save('Excel_Workbook.xls')

Entering a Date into a Cell
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save('Excel_Workbook.xls')

Adding a Formula to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])
workbook.save('Excel_Workbook.xls')

Adding a Hyperlink to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) # Outputs the text "Google" linking to http://www.google.com
workbook.save('Excel_Workbook.xls')

Merging Columns and Rows
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write_merge(0, 0, 0, 3, 'First Merge') # Merges row 0's columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style) # Merges row 1 through 2's columns 0 through 3.
workbook.save('Excel_Workbook.xls')

Setting the Alignment for the Contents of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

Adding Borders to a Cell
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

Setting the Background Color of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

TODO: Things Left to Document
- Panes -- separate views which are always in view
- Border Colors (documented above, but not taking effect as it should)
- Border Widths (document above, but not working as expected)
- Protection
- Row Styles
- Zoom / Manification
- WS Props?
Source Code for reference available at: https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

用python讀寫excel的方法

用python讀寫excel的方法:本文實(shí)例講述了用python讀寫excel的方法。分享給大家供大家參考。具體如下: 最近需要從多個(gè)excel表里面用各種方式整理一些數(shù)據(jù),雖然說(shuō)原來(lái)用過(guò)java做這類事情,但是由于最近在學(xué)python,所以當(dāng)然就決定用python嘗試一下了。發(fā)現(xiàn)python果然簡(jiǎn)潔很多。
推薦度:
標(biāo)簽: 方法 excel 的方法
  • 熱門焦點(diǎn)

最新推薦

猜你喜歡

熱門推薦

專題
Top