目的:实现用python做excel的读取、新增、修改操作。
环境:ubuntu 16.04 Python 3.5.2
用python读写文档,一般是操作txt文件或者可以用记事本打开的文件,因为这个操作很直接,不需要导入其他模块,但如果想要对excel表格进行操作,就需要导入其他模块,包括:xlrd(读取),xlwt(写入),xlutils(复制),一般是这三个模块,且需要另外下载,http://pypi.python.org/pypi/模块名。
表格的读取:
读取只需要导入xlrd模块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import xlrd
filename = 'test.xls'
book = xlrd.open_workbook(filename)
sheel_1 = book.sheet_by_index( 0 )
print ( "Worksheet name(s): " ,book.sheet_names()[ 0 ])
print ( 'book.nsheets' ,book.nsheets)
print ( 'sheel_1.name:' ,sheel_1.name, 'sheel_1.nrows:' ,sheel_1.nrows, 'sheel_1.ncols:' ,sheel_1.ncols)
print ( 'A1:' ,sheel_1.cell_value(rowx = 0 ,colx = 1 ))
print ( 'A2:' ,sheel_1.cell_value( 0 , 2 ))
|
表格的新增:
新增只需要导入xlwt模块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import xlwt
filename = 'test.xls'
book = xlwt.Workbook()
sheet_1 = book.add_sheet( 'hello' )
sheel_2 = book.add_sheet( 'word' )
sheet_1.write( 0 , 0 , 'hello' )
sheet_1.write( 0 , 1 , 'world' )
row1 = sheet1.row( 1 )
row1.write( 0 , 'A2' )
row1.write( 1 , 'B2' )
sheet_1.col( 0 ).width = 10000
sheet_2 = book.get_sheet( 1 )
sheet_2.row( 0 ).write( 0 , 'Sheet 2 A1' )
sheet_2.row( 0 ).write( 1 , 'Sheet 2 B1' )
sheet_2.flush_row_data()
sheet_2.write( 1 , 0 , 'Sheet 2 A3' )
sheet_2.col( 0 ).width = 5000
sheet_2.col( 0 ).hidden = True
book.save(filename)
|
修改已经存在的表格:
一般修改表格步骤:导入模块--xlrd读取表格--xlutils复制读取的表格--xlwt对表格修改--xlwt保存表格--删除旧表格。
解析:对excel同时读写是不行的,细心会发现office操作表格时也是这个步骤,先是读取,如果修改了数据,会先复制一份,产生一个带$的临时隐藏文件,修改是在临时文件上操作,当用户保存时会删除旧的文件,把临时文件命名为旧文件名,感觉就像直接读写了表格,所以你没有正常关闭的表格会有一个临时文件,你没保存的东西全部在里面,也可能是部分。
下面演示一下实际python应用步骤:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import xlrd
import xlwt
from xlutils.copy import copy
filename = 'test.xls'
book_r = xlrd.open_workbook(filename)
book_w = copy(book_r)
sheet_1 = book_w.get_sheet( 0 )
text = ‘This is a test of Ricky.'
row = 1
col = 2
sheet_1.write(row, col, text)
os.remove(filename)
book_w.save(filename)
|
说明:
1)上面那么多定义是为了说明参数的位置和意义,可以直接把值写入参数位置,但参数使用变量可以方便复用,比如在循环中;
2)读取表格的文本内容需要用value();
3)如果想要保留源文件的格式,打开部分的需要写成:
1
|
book_r = xlrd.open_workbook(filename, formatting_info = True )
|
4)sheet没有save,workbook才有save。
一次性读写表格可以参看方法二(私链)。
本文转自RickyHuL51CTO博客,原文链接:http://blog.51cto.com/rickyh/1943649 ,如需转载请自行联系原作者