簡介html
xlrd是python的一個第三方模塊,能夠實現跨平臺讀Microsoft Excel文件。(它有一個兄弟叫xlwt,專一於寫Excel文件。)python
它並不像win2com那樣藉助COM技術來訪問Excel,而是直接分析Excel文件格式,從中解析數據。所以你能夠在任何支持python的平臺上使用excel文件。這一點它比win2com要優秀得多。spa
另外,它對unicode支持的很好,這也是我青睞它的重要緣由。.net
它的工做原理所限,咱們不能指望它覆蓋Excel所有的功能,訪問到所有的數據。excel
好比,下面這些數據類型xlrd會忽略掉:code
圖表,宏,圖片等嵌入對象(包括嵌入的worksheet)。orm
VBA模塊。htm
公式(只能識別公式的計算結果,而不是公式自己)。對象
註釋。圖片
連接。
但一些簡單的讀取仍是駕輕就熟的,這已經能知足大多數狀況下的需求。
如今它能支持的Excel版本包括:2004, 2003, XP, 2000, 97, 95, 5.0, 4.0, 3.0, 2.1, 2.0。 官方未說明它是否能支持Excel 2007。
它有兩個分支,分別是:
xlrd (http://pypi.python.org/pypi/xlrd) 針對Python 2.x系列。
xlrd3(http://pypi.python.org/pypi/xlrd3) 針對Python 3.x系列。
這兩個分支是100%兼容的,也就是說,它們的使用徹底同樣,你在3.x系列中怎麼用xlrd,在2.x系列中仍然這麼用。
如下的實際操做都使用xlrd3,在python 3.2下完成。
試用
假設咱們有一個文件叫test.xls,位於D:\Workspace\Python\xlrd3-test\test.xls
其內容以下:
clipboard[1]
這是一張9行4列的PC主機報價單,固然,價格全是扯淡。
下面使用xlrd程序將PC這張表的內容打印出來。
01 import xlrd3
02
03 def main():
04 xlsfile=xlrd3.open_workbook("D:\\Workspace\\Python\\xlrd3-test\\test.xls")
05 try:
06 mysheet = xlsfile.sheet_by_name("PC")
07 except:
08 print("no sheet in %s named PC")
09 return
10
11 # total rows and cols
12 print("%d rows, %d cols"%(mysheet.nrows, mysheet.ncols))
13
14 for row in range(0, mysheet.nrows):
15 temp=""
16 for col in range(0, mysheet.ncols):
17 if mysheet.cell(row, col).value != None:
18 temp+=str(mysheet.cell(row, col).value)+"\t"
19 print(temp)
20
21 if __name__ == '__main__':
22 main()
輸出:
clipboard[2]
將lang下的txt文件導出到一個excel裏:
01.
import
os
02.
import
glob
03.
path
=
os.getcwd()
04.
files
=
glob.glob(
'../trunk/Resource/lang/ja/*.txt'
)
05.
import
xlwt3
06.
if
len(files) >
0
:
07.
wb
=
xlwt3.Workbook()
08.
for
file
in
files:
09.
fileName
=
file.split(
'\\')[1].split('
.')[
0
]
10.
print
(fileName)
11.
ws
=
wb.add_sheet(fileName)
12.
with open(file, encoding
=
'utf-8'
) as a_file:
13.
line_number
=
0
14.
for
a_line
in
a_file:
15.
a_line
=
a_line.rstrip()
16.
mark
=
a_line.find(
"="
)
17.
ws.write(line_number,
0
, a_line[
0
:mark])
18.
ws.write(line_number,
1
, a_line[mark
+
1
:])
19.
ws.col(
0
).width
=
8000
20.
ws.col(
1
).width
=
40000
21.
line_number
+
=
1
22.
a_file.close()
23.
wb.save(
'langPack_ja.xls'
)
將sourceExcel下的excel文件導出爲各txt文件:
01.
import
os
02.
import
glob
03.
import
xlrd3 as xlrd
04.
import
re
05.
06.
path
=
os.getcwd()
07.
08.
files
=
glob.glob(
'sourceExcel/*'
)
09.
10.
for
file
in
files:
11.
wb
=
xlrd.open_workbook(file)
12.
for
sheetName
in
wb.sheet_names():
13.
txtFile
=
open(
'outputTxts/'
+
sheetName
+
'.txt'
, mode
=
'w'
, encoding
=
'utf-8'
)
14.
sheet
=
wb.sheet_by_name(sheetName)
15.
for
rownum
in
range(sheet.nrows):
16.
v1
=
sheet.cell(rownum,
0
).value
17.
if
(type(v1)
=
=
float):
18.
v1
=
str(v1)
19.
v1
=
re.sub(
'\.0*$'
, "", v1)
20.
v1
=
v1.rstrip()
21.
v2
=
sheet.cell(rownum,
1
).value
22.
if
(type(v2)
=
=
float):
23.
v2
=
str(v2)
24.
v2
=
re.sub(
'\.0*$'
, "", v2)
25.
v2
=
v2.rstrip()
26.
dataStr
=
v1
+
'='
+
v2
+
'\n'
27.
txtFile.write(dataStr)
28.
txtFile.close()