-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
988 lines (714 loc) · 44.5 KB
/
index.html
File metadata and controls
988 lines (714 loc) · 44.5 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Python excel by Qijiang60</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">
</head>
<body>
<section class="page-header">
<h1 class="project-name">Python excel</h1>
<h2 class="project-tagline"></h2>
<a href="https://github.com/Qijiang60/python_excel" class="btn">View on GitHub</a>
<a href="https://github.com/Qijiang60/python_excel/zipball/master" class="btn">Download .zip</a>
<a href="https://github.com/Qijiang60/python_excel/tarball/master" class="btn">Download .tar.gz</a>
</section>
<section class="main-content">
<h3>
<a id="welcome-to-github-pages" class="anchor" href="#welcome-to-github-pages" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3>
<p>1、导入模块</p>
<pre><code> import xlrd
</code></pre>
<p>2、打开Excel文件读取数据</p>
<pre><code> data = xlrd.open_workbook('excelFile.xls')
</code></pre>
<p>3、使用技巧</p>
<pre><code> 获取一个工作表
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取
获取整行和整列的值(数组)
</code></pre>
<p>
table.row_values(i)</p>
<pre><code> table.col_values(i)
获取行数和列数
</code></pre>
<p>
nrows = table.nrows</p>
<pre><code> ncols = table.ncols
循环行列表数据
for i in range(nrows ):
print table.row_values(i)
</code></pre>
<p>单元格
cell_A1 = table.cell(0,0).value</p>
<p>cell_C4 = table.cell(2,3).value</p>
<p>使用行列索引
cell_A1 = table.row(0)[0].value</p>
<p>cell_A2 = table.col(1)[0].value</p>
<p>简单的写入
row = 0</p>
<p>col = 0</p>
<h1>
<a id="类型-0-empty1-string-2-number-3-date-4-boolean-5-error" class="anchor" href="#%E7%B1%BB%E5%9E%8B-0-empty1-string-2-number-3-date-4-boolean-5-error" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error</h1>
<p>ctype = 1 value = '单元格的值'</p>
<p>xf = 0 # 扩展的格式化</p>
<p>table.put_cell(row, col, ctype, value, xf)</p>
<p>table.cell(0,0) #单元格的值'</p>
<p>table.cell(0,0).value #单元格的值'</p>
<h3>
<a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Designer Templates</h3>
<h1>
<a id="---coding-utf-8---" class="anchor" href="#---coding-utf-8---" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>-<em>- coding: utf-8 -</em>-</h1>
<p>import xdrlib ,sys
import xlrd
def open_excel(file= 'file.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)</p>
<h1>
<a id="根据索引获取excel表格中的数据---参数fileexcel文件路径-----colnameindex表头列名所在行的所以--by_index表的索引" class="anchor" href="#%E6%A0%B9%E6%8D%AE%E7%B4%A2%E5%BC%95%E8%8E%B7%E5%8F%96excel%E8%A1%A8%E6%A0%BC%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE---%E5%8F%82%E6%95%B0fileexcel%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84-----colnameindex%E8%A1%A8%E5%A4%B4%E5%88%97%E5%90%8D%E6%89%80%E5%9C%A8%E8%A1%8C%E7%9A%84%E6%89%80%E4%BB%A5--by_index%E8%A1%A8%E7%9A%84%E7%B4%A2%E5%BC%95" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>根据索引获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_index:表的索引</h1>
<p>def excel_table_byindex(file= 'file.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):</p>
<pre><code> row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
</code></pre>
<h1>
<a id="根据名称获取excel表格中的数据---参数fileexcel文件路径-----colnameindex表头列名所在行的所以--by_namesheet1名称" class="anchor" href="#%E6%A0%B9%E6%8D%AE%E5%90%8D%E7%A7%B0%E8%8E%B7%E5%8F%96excel%E8%A1%A8%E6%A0%BC%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE---%E5%8F%82%E6%95%B0fileexcel%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84-----colnameindex%E8%A1%A8%E5%A4%B4%E5%88%97%E5%90%8D%E6%89%80%E5%9C%A8%E8%A1%8C%E7%9A%84%E6%89%80%E4%BB%A5--by_namesheet1%E5%90%8D%E7%A7%B0" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>根据名称获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_name:Sheet1名称</h1>
<p>def excel_table_byname(file= 'file.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:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list</p>
<p>def main():
tables = excel_table_byindex()
for row in tables:
print row</p>
<p>tables = excel_table_byname()
for row in tables:
print row</p>
<p>if <strong>name</strong>=="<strong>main</strong>":
main()</p>
<h3>
<a id="creating-pages-manually" class="anchor" href="#creating-pages-manually" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Creating pages manually</h3>
<p> 今天一同学给我发来一个Excel文件,让我帮他找一些信息,打开一开 8000多条数据。自己手工处理是不可能完成的的啦。作为一名程序员,当然要用程序来处理。处理生活中的问题当然是Python最为方便啦。利用万能的 Google 搜索 Python Excel,点击第一条结果<a href="http://www.python-excel.org/">http://www.python-excel.org/</a> ,发先这个东西 能够跨平台处理 Excel。废话不多说,按照文档一步步去做,要安装 三个包 xlrd(用于读Excel), xlwt(用于写Excel),xlutils(处理Excel的工具箱)。</p>
<p> 上面的英文文档很齐全,这里就不多说了,因为我只需要获取Excel里面的数据,所以只要简单的读取出来。
from xlrd import open_workbook
import re</p>
<h1>
<a id="创建一个用于读取sheet的生成器依次生成每行数据row_count-用于指定读取多少行-col_count-指定用于读取多少列" class="anchor" href="#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E7%94%A8%E4%BA%8E%E8%AF%BB%E5%8F%96sheet%E7%9A%84%E7%94%9F%E6%88%90%E5%99%A8%E4%BE%9D%E6%AC%A1%E7%94%9F%E6%88%90%E6%AF%8F%E8%A1%8C%E6%95%B0%E6%8D%AErow_count-%E7%94%A8%E4%BA%8E%E6%8C%87%E5%AE%9A%E8%AF%BB%E5%8F%96%E5%A4%9A%E5%B0%91%E8%A1%8C-col_count-%E6%8C%87%E5%AE%9A%E7%94%A8%E4%BA%8E%E8%AF%BB%E5%8F%96%E5%A4%9A%E5%B0%91%E5%88%97" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>创建一个用于读取sheet的生成器,依次生成每行数据,row_count 用于指定读取多少行, col_count 指定用于读取多少列</h1>
<p>def readsheet(s, row_count=-1, col_cout=-1):#
# Sheet 有多少行
nrows = s.nrows
# Sheet 有多少列
ncols = s.ncols
row_count = (row_count if row_count > 0 else nrows)
col_count = (col_count if col_count > 0 else ncols)
row_index = 0
while row_index < row_count:
yield [s.cell(row_index, col).value for col in xrange(col_count)]
row_index += 1</p>
<p>wb = open_workbook('simple.xls') #打开Excel文件</p>
<h1>
<a id="读取excel中所有的sheet" class="anchor" href="#%E8%AF%BB%E5%8F%96excel%E4%B8%AD%E6%89%80%E6%9C%89%E7%9A%84sheet" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>读取Excel中所有的Sheet</h1>
<p>for s in wb.sheets():
for row in readsheet(s, 10, 10):# 只读取每个Sheet的前10行,前10列(当然你要确保,你的数据多余10行,且多余10列)
print row</p>
<p> 非常简单, 主要用到 xlrd 四个特性 open_workbook , wb.sheets(), s.nrows-(行数),s.ncols -(列数), s.cell(row, col).value- (获取指定单位处的值)。</p>
<p> 这几个函数用于处理一般的读取操作完全够了。</p>
<h3>
<a id="authors-and-contributors" class="anchor" href="#authors-and-contributors" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Authors and Contributors</h3>
<p><a href="http://www.cnblogs.com/zhoujie/p/python18.html">http://www.cnblogs.com/zhoujie/p/python18.html</a>
最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异,而且不太能满足需求,不过经过一番对源码的"研究"(用此一词让我觉得颇有成就感)之后,基本解决了日常所需。主要记录使用过程的常见问题及解决。</p>
<p> python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。可从这里下载<a href="https://pypi.python.org/pypi%E3%80%82%E4%B8%8B%E9%9D%A2%E5%88%86%E5%88%AB%E8%AE%B0%E5%BD%95python%E8%AF%BB%E5%92%8C%E5%86%99excel">https://pypi.python.org/pypi。下面分别记录python读和写excel</a>.</p>
<p>python读excel——xlrd</p>
<p>这个过程有几个比较麻烦的问题,比如读取日期、读合并单元格内容。下面先看看基本的操作:</p>
<p>首先读一个excel文件,有两个sheet,测试用第二个sheet,sheet2内容如下:</p>
<p>python 对 excel基本的操作如下:</p>
<h1>
<a id="---coding-utf-8----1" class="anchor" href="#---coding-utf-8----1" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>-<em>- coding: utf-8 -</em>-</h1>
<p>import xlrd
import xlwt
from datetime import date,datetime</p>
<p>def read_excel():
# 打开文件
workbook = xlrd.open_workbook(r'F:\demo.xlsx')
# 获取所有sheet
print workbook.sheet_names() # [u'sheet1', u'sheet2']
sheet2_name = workbook.sheet_names()[1]</p>
<pre><code># 根据sheet索引或者名称获取sheet内容
sheet2 = workbook.sheet_by_index(1) # sheet索引从0开始
sheet2 = workbook.sheet_by_name('sheet2')
# sheet的名称,行数,列数
print sheet2.name,sheet2.nrows,sheet2.ncols
# 获取整行和整列的值(数组)
rows = sheet2.row_values(3) # 获取第四行内容
cols = sheet2.col_values(2) # 获取第三列内容
print rows
print cols
# 获取单元格内容
print sheet2.cell(1,0).value.encode('utf-8')
print sheet2.cell_value(1,0).encode('utf-8')
print sheet2.row(1)[0].value.encode('utf-8')
# 获取单元格内容的数据类型
print sheet2.cell(1,0).ctype
</code></pre>
<p>if <strong>name</strong> == '<strong>main</strong>':
read_excel()</p>
<h3>
<a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Support or Contact</h3>
<p><a href="http://my.oschina.net/dddttttt/blog/466103">http://my.oschina.net/dddttttt/blog/466103</a></p>
<p>Python xlrd、xlwt、xlutils读取、修改Excel文件</p>
<p>一、xlrd读取excel</p>
<p>这里介绍一个不错的包xlrs,可以工作在任何平台。这也就意味着你可以在Linux下读取Excel文件。</p>
<p>首先,打开workbook;<br>
import xlrd
wb = xlrd.open_workbook('myworkbook.xls')</p>
<p>检查表单名字:<br>
wb.sheet_names()</p>
<p>得到第一张表单,两种方式:索引和名字<br>
sh = wb.sheet_by_index(0)
sh = wb.sheet_by_name(u'Sheet1')</p>
<p>递归打印出每行的信息:<br>
for rownum in range(sh.nrows):
print sh.row_values(rownum)</p>
<p>如果只想返回第一列数据:
first_column = sh.col_values(0)</p>
<p>通过索引读取数据:<br>
cell_A1 = sh.cell(0,0).value
cell_C4 = sh.cell(rowx=3,colx=2).value</p>
<p>注意:这里的索引都是从0开始的。</p>
<p>一、安装xlrd模块</p>
<p>到python官网下载<a href="http://pypi.python.org/pypi/xlrd%E6%A8%A1%E5%9D%97%E5%AE%89%E8%A3%85%EF%BC%8C%E5%89%8D%E6%8F%90%E6%98%AF%E5%B7%B2%E7%BB%8F%E5%AE%89%E8%A3%85%E4%BA%86python">http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python</a> 环境。</p>
<p>二、使用介绍</p>
<p>1、导入模块</p>
<pre><code> import xlrd
</code></pre>
<p>2、打开Excel文件读取数据</p>
<pre><code> data = xlrd.open_workbook('excelFile.xls')
</code></pre>
<p>3、使用技巧</p>
<pre><code> 获取一个工作表
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)
获取行数和列数
</code></pre>
<p> nrows = table.nrows</p>
<pre><code> ncols = table.ncols
循环行列表数据
for i in range(nrows ):
print table.row_values(i);
</code></pre>
<p>单元格</p>
<p>cell_A1 = table.cell(0,0).value</p>
<p>cell_C4 = table.cell(2,3).value</p>
<p>使用行列索引</p>
<p>cell_A1 = table.row(0)[0].value</p>
<p>cell_A2 = table.col(1)[0].value</p>
<p>简单的写入</p>
<p>row = 0</p>
<p>col = 0</p>
<h1>
<a id="类型-0-empty1-string-2-number-3-date-4-boolean-5-error-1" class="anchor" href="#%E7%B1%BB%E5%9E%8B-0-empty1-string-2-number-3-date-4-boolean-5-error-1" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error</h1>
<p>ctype = 1 value = '单元格的值'</p>
<p>xf = 0 # 扩展的格式化 </p>
<p>table.put_cell(row, col, ctype, value, xf)</p>
<p>table.cell(0,0) #单元格的值'</p>
<p>table.cell(0,0).value #单元格的值'</p>
<p>二、xlwt写excel </p>
<p>这里介绍一个不错的包xlwt,可以工作在任何平台。这也就意味着你可以在Linux下保存Excel文件。</p>
<p>基本部分</p>
<p>在写入Excel表格之前,你必须初始化workbook对象,然后添加一个workbook对象。比如:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')</p>
<p>这样表单就被创建了,写入数据也很简单:</p>
<h1>
<a id="indexing-is-zero-based-row-then-column" class="anchor" href="#indexing-is-zero-based-row-then-column" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>indexing is zero based, row then column</h1>
<p>sheet.write(0,1,'test text')</p>
<p>之后,就可以保存文件(这里不需要想打开文件一样需要close文件):
wbk.save('test.xls')</p>
<p>深入探索</p>
<p>worksheet对象,当你更改表单内容的时候,会有警告提示。
sheet.write(0,0,'test')
sheet.write(0,0,'oops')</p>
<h1>
<a id="returns-error" class="anchor" href="#returns-error" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>returns error:</h1>
<h1>
<a id="exception-attempt-to-overwrite-cell" class="anchor" href="#exception-attempt-to-overwrite-cell" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Exception: Attempt to overwrite cell:</h1>
<h1>
<a id="sheetnameusheet-1-rowx0-colx0" class="anchor" href="#sheetnameusheet-1-rowx0-colx0" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>sheetname=u'sheet 1' rowx=0 colx=0</h1>
<p>解决方式:使用cell_overwrite_ok=True来创建worksheet:
sheet2 = wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
sheet2.write(0,0,'some text')
sheet2.write(0,0,'this should overwrite')</p>
<p>这样你就可以更改表单2的内容了。</p>
<p>更多</p>
<h1>
<a id="initialize-a-style" class="anchor" href="#initialize-a-style" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Initialize a style</h1>
<p>style = xlwt.XFStyle()</p>
<h1>
<a id="create-a-font-to-use-with-the-style" class="anchor" href="#create-a-font-to-use-with-the-style" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Create a font to use with the style</h1>
<p>font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True</p>
<h1>
<a id="set-the-styles-font-to-this-new-one-you-set-up" class="anchor" href="#set-the-styles-font-to-this-new-one-you-set-up" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Set the style's font to this new one you set up</h1>
<p>style.font = font</p>
<h1>
<a id="use-the-style-when-writing" class="anchor" href="#use-the-style-when-writing" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Use the style when writing</h1>
<p>sheet.write(0, 0, 'some bold Times text', style)</p>
<p>xlwt 允许你每个格子或者整行地设置格式。还可以允许你添加链接以及公式。其实你可以阅读源代码,那里有很多例子:</p>
<pre><code>dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.
</code></pre>
<p>三 xlutils修改excel </p>
<p>Python中一般使用xlrd(excel read)来读取Excel文件,使用xlwt(excel write)来生成Excel文件(可以控制Excel中单元格的格式),需要注意的是,用xlrd读 取excel是不能对其进行操作的:xlrd.open_workbook()方法返回xlrd.Book类型,是只读的,不能对其进行操作。而 xlwt.Workbook()返回的xlwt.Workbook类型的save(filepath)方法可以保存excel文件。因此对于读取和生成Excel文件都非常容易处理,但是对于已经存在的Excel文件进行修改就比较麻烦了。不过,还有一个xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已,如下图:</p>
<p>xlutils.copy模块的copy()方法实现了这个功能,示例代码如下:</p>
<p>from xlrd import open_workbook
from xlutils.copy import copy</p>
<p>rb = open_workbook('m:\1.xls')</p>
<h1>
<a id="通过sheet_by_index获取的sheet没有write方法" class="anchor" href="#%E9%80%9A%E8%BF%87sheet_by_index%E8%8E%B7%E5%8F%96%E7%9A%84sheet%E6%B2%A1%E6%9C%89write%E6%96%B9%E6%B3%95" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>通过sheet_by_index()获取的sheet没有write()方法</h1>
<p>rs = rb.sheet_by_index(0)</p>
<p>wb = copy(rb)</p>
<h1>
<a id="通过get_sheet获取的sheet有write方法" class="anchor" href="#%E9%80%9A%E8%BF%87get_sheet%E8%8E%B7%E5%8F%96%E7%9A%84sheet%E6%9C%89write%E6%96%B9%E6%B3%95" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>通过get_sheet()获取的sheet有write()方法</h1>
<p>ws = wb.get_sheet(0)
ws.write(0, 0, 'changed!')</p>
<p>wb.save('m:\1.xls')</p>
<p>四 参考 </p>
<p><a href="http://pypi.python.org/pypi/xlrd">http://pypi.python.org/pypi/xlrd</a></p>
<p><a href="http://pypi.python.org/pypi/xlwt">http://pypi.python.org/pypi/xlwt</a></p>
<p><a href="http://pypi.python.org/pypi/xlutils">http://pypi.python.org/pypi/xlutils</a></p>
<p>本文整合自 </p>
<p><a href="http://www.leyond.info/write-excel-files-with-python-using-xlwt/">http://www.leyond.info/write-excel-files-with-python-using-xlwt/</a></p>
<p><a href="http://www.leyond.info/read-excel-from-python-using-xlrs/">http://www.leyond.info/read-excel-from-python-using-xlrs/</a></p>
<p><a href="http://www.zhlwish.com/2010/10/09/python_edit_excel/">http://www.zhlwish.com/2010/10/09/python_edit_excel/</a></p>
<h3>
<a id="support-or-contact-1" class="anchor" href="#support-or-contact-1" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Support or Contact</h3>
<p>Python读取和写入Excel文件整转载▼
标签: 杂谈 分类: python
详见百度空间:<a href="http://hi.baidu.com/ilovelittree/item/62270cdf54fff132d80e4468">http://hi.baidu.com/ilovelittree/item/62270cdf54fff132d80e4468</a></p>
<p>学习用Python处理Excel文件,这里主要用xlrd和xlwt模块,用前需要安装!本文是来自几篇博客和官网tutorial的整理,主要是一个入门。更多的处理Excel的方法请到官网学习,链接为:<a href="http://www.simplistix.co.uk/presentations/python-excel.pdf">http://www.simplistix.co.uk/presentations/python-excel.pdf</a>
另外,几篇博客的参考资料:
<a href="http://syue.com/Software/Language/Python/21655.html">http://syue.com/Software/Language/Python/21655.html</a>
<a href="http://blog.csdn.net/wangxiaoyan1988/article/details/6562374">http://blog.csdn.net/wangxiaoyan1988/article/details/6562374</a>
<a href="http://www.2cto.com/kf/201207/140006.html">http://www.2cto.com/kf/201207/140006.html</a></p>
<p>A:Excel数据的类型及组织方式</p>
<p>每一个Excel数据文件从上至下分为三个层级的对象:
workbook: 每一个Excel文件就是一个workbook。
sheet: 每一个workbook中可以包含多个sheet,具体就对应Excel中我们在左下脚所看到的“sheet1”,“sheet2”等。
cell: 每一个sheet就是我们通常所看到的一个表格,可以含有m行,n列,每个确定的行号,列号所对应的一个格子就是一个cell。</p>
<p>B: 从Excel中读取数据</p>
<p>从一个既有的xlsx文件中读取数据,按照Excel文件的三个层级,分别做以下三个步骤</p>
<ol>
<li>打开workbook:
import xlrd
book = xlrd.open_workbook("myfile.xls") #book就赋值为一个Excel文件了</li>
</ol>
<p>注:
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对象实例列表</p>
<ol>
<li><p>打开所需的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对象的序列</p></li>
<li><p>获取对应cell的值:
cell=sh.cell(rowx=29, colx=3) #根据给出的行和列的参数获取得到cell类,返回一个Cell类实例对象
sh.cell_value(rowx=29, colx=3)</p></li>
</ol>
<p>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)这样设置的时候</p>
<p>4.一个读取Excel的例子</p>
<p>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)</p>
<p>C: Writing Excel Files</p>
<p>All the examples shown below can be found in the xlwt directory of the course material.读Excel xlrd模块,写用xlwt模块</p>
<ol>
<li> Creating elements within a Workbook创建一个Excel文件</li>
</ol>
<p>Import xlwt
wb=xlwt.Workbook(“zc.xls”) #Workbook 首字母大写</p>
<ol>
<li> Worksheets 添加Sheet</li>
</ol>
<p>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.</p>
<p>Sheet1=wb.add_sheet(“sheetname”)</p>
<ol>
<li> Rows and Columns 行与列的表示:</li>
</ol>
<p>row1 = sheet1.row(1)
col0=sheet2.col(0)</p>
<ol>
<li> Cells</li>
</ol>
<p>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')</p>
<ol>
<li> svave 保存文件:</li>
</ol>
<p>wb.save(“zc.xls”)</p>
<ol>
<li> 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')</li>
</ol>
<p>D: 稍微复杂的例子和巩固
Ex1:</p>
<p>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)</p>
<p>cell_value = sh.cell_value(1,1)
print cell_value</p>
<p>row_list = []
for i in range(1, nrows):
row_data = sh.row_values(i)
row_list.append(row_data)</p>
<p>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 <strong>name</strong> == '<strong>main</strong>':
47 t = OperExcel()
48 t.rExcel('test.xls','test')
49 t.wExcel('test','1.xls')
50 # 作者:sunrise</p>
<h3>
<a id="support-or-contact-2" class="anchor" href="#support-or-contact-2" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Support or Contact</h3>
<pre><code>因为经常会涉及到从Excel表中导数据,所以就学习了python的xlrd来读取excel中的数据。
</code></pre>
<p>1.xlrd的安装
xlrd是python的第三方库,所以是需要自己安装的,可以在python的官网<a href="http://pypi.python.org/pypi/xlrd%E4%B8%8B%E8%BD%BD%E8%AF%A5%E6%A8%A1%E5%9D%97%E6%9D%A5%E5%AE%89%E8%A3%85%EF%BC%8C%E4%B9%9F%E5%8F%AF%E4%BB%A5%E9%80%9A%E8%BF%87%E5%85%B6%E4%BB%96%E6%89%8B%E6%AE%B5%EF%BC%8C%E6%AF%94%E5%A6%82easy_install%E6%88%96%E8%80%85pip%E5%95%A5%E7%9A%84%EF%BC%8C%E6%88%91%E5%B7%B2%E7%BB%8F%E5%AE%89%E8%A3%85%E5%A5%BDpip%E6%89%80%E4%BB%A5%E5%B0%B1%E7%94%A8%E6%9C%80%E6%87%92%E7%9A%84%E6%96%B9%E5%BC%8F%E6%9D%A5%E5%AE%89%E8%A3%85%E4%BA%86pip">http://pypi.python.org/pypi/xlrd下载该模块来安装,也可以通过其他手段,比如easy_install或者pip啥的,我已经安装好pip所以就用最懒的方式来安装了pip</a> install xlrd来安装。
2.分析excel文件的层级对象
要读取excel的数据,就要了解excel的结构,根据excel的结构一层一层的去读取数据。
excel有三层级对象,workbook,sheet,和cell。一个excel文件就是一个workbook,所以在最初我们必须要打开这个excel文件,也就是workbook。sheet我们都很熟悉,就是表,我们都知道一个excel文件有时候会有很多的表,所以我们必须要选择是读取哪个表的数据,最后才是cell,cell其实就是格子,excel的表格就是一个二维数组,cell就是这个表格中的最小单元,也就是我们读取数据存储的地方。
3.xlrd读取excel的基本操作
python是一个很强大的脚本语言,之所以强大是因为它的库很强大,xlrd作为python的第三方库已经将读取excel文件的各个操作封装好了,我们只需要调用它提供的一些接口就可以很快速简单的读取数据。下面看看最基本的操作。
1).打开一个excel文件得到数据:
data = xlrd.open_workbook("test.xls")</p>
<p>2).获取一个表格数据
table = data.sheets()[0] #通过索引获取
table = data.sheet_by_index(0) #通过索引获取
table = data.sheet_by_name('set') #通过表名获取</p>
<p>3).获取表格数据
nrows = table.nrows #行数
ncols = table.ncols #列数
data = table.cell(nrow, ncol).value #得到表格数据</p>
<h1>
<a id="获取每行每列的数据" class="anchor" href="#%E8%8E%B7%E5%8F%96%E6%AF%8F%E8%A1%8C%E6%AF%8F%E5%88%97%E7%9A%84%E6%95%B0%E6%8D%AE" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>获取每行每列的数据</h1>
<p>for i in range(0, nrows):
for j in range(0, ncols):
data = table.cell(i, j).value</p>
<h3>
<a id="support-or-contact-3" class="anchor" href="#support-or-contact-3" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Support or Contact</h3>
<p>数据处理:Python使用xlrd包读取Excel表格数据NOV,24 2013
在日常的数据处理工作中,我们经常会有批量处理Excel文件的需求。比如历史上定期的Excel报价表格,或者是会员信息等等。针对多个文件的数据处理,VBA宏是一种方案,而用Python进行处理也是一种好的办法。</p>
<p>这两天看见人力忙着核对绩效,手动工作量十分大,于是我主动提出帮她们减轻负担啦!她们的需求是每月有一批绩效考核文件,需要打开每个核对与汇总绩效成绩是否一致。<br>
说明:Python的Excel包有很多,我使用的是xlrd包,地址: <a href="https://pypi.python.org/pypi/xlrd/0.9.2">https://pypi.python.org/pypi/xlrd/0.9.2</a> 。
首先我们要明白excel文件的组织结构:</p>
<p>cell:单元格。就是excel表中一个个的小格子,我们在里面输入数据,也可以通过行与列来表示这个小格子的位置;
sheet:工作表。我们通常新建一个新的excel,会在excel界面的底部看到有个3个新的工作表-”sheet1,sheet2,sheet3“。一个工作表是由N多个cell单元格组成,他是excel文件的中层结构。
Excel文件:office官方文档称呼为”工作簿“,它由多个sheet组成,是excel的最高层。
理解了上面excel组织结构后,我们就能很好的理解excel的相关函数了。
从最简单的一段代码说起:</p>
<p>1: import xlrd #引入包
2: book = xlrd.open_workbook("myfile.xls")
3: #创建一个book class,打开excel文件
4: print "The number of worksheets is", book.nsheets
5: # nsheets属性记录一个excel文件中有多少个sheet
6: print "Worksheet name(s):", book.sheet_names()
7: #返回sheet name的list
8: sh = book.sheet_by_index(0)<br>
9: #获取一个sheet对象
10: print sh.name, sh.nrows, sh.ncols<br>
11: # sheet的属性:name,rows,cols
12: print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
13: #定位一个cell
14: for rx in range(sh.nrows):
15: print sh.row(rx) #按照row输出excel数据
16: </p>
<p>上面这段代码打开了一个叫”myfile.xls“的文件,使用的方法是xlrd.open_workbook()。我们知道一个excel文件中可以有多个sheet,所以我们可以用book.nsheets属性知道这个文件有多少个sheet.</p>
<p>接下来是获取sheet的操作:使用book.sheet_by_index(0)获取第一个sheet对象。我们获取sheet对象,可以使用index定位,也可以使用name定位,比如sheet_by_name(xxx)。</p>
<p>获取完sheet对象后,就可以读取具体的单元格数据啦。按行读取,按列读取等可以按需选择。</p>
<p>附:之前需求的处理代码,其实很简单:</p>
<p>1: def get_kpi(file):
2: book = xlrd.open_workbook(file)<br>
3: #print "The number of worksheets is", book.nsheets
4: for shnum in range(0,book.nsheets):
5: rowx=0
6: sh = book.sheet_by_index(shnum)
7: if re.search('he',sh.name)!=None:
8: pass
9: else:
10: rowx=sh.col_values(0).index(u'总评得分:')
11: for rVaule in sh.row_slice(rowx,1,3):
12: if rVaule.ctype==2:
13: print sh.name,rVaule.value</p>
<h3>
<a id="fsfsdfsdf" class="anchor" href="#fsfsdfsdf" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>fsfsdfsdf</h3>
<p><a href="https://gerald.top/note/python-excel">https://gerald.top/note/python-excel</a>
Python读写Excel文件</p>
<p>Sep 29, 2014
背景</p>
<p>其实我本来是不愿意面对Python读写Excel文件这个问题的,因为Excel文件的标准并不公开,而且发展至今有了很多版本,所以即使通过第三方库实现了读写,也依然不能保证没有兼容性问题,因此以前遇到这个问题的时候,我都是选择逃避,使用CSV/TSV之类的读写来替代,绝无后顾之忧。</p>
<p>但是,这一次因为最终需要生成包含多个表单的Excel文件,因此还是直接操作比较省事,至于为什么用Python,因为……文字处理哪家强?(脑补一下。。)</p>
<p>牵涉到的问题:</p>
<p>Python版本支持?</p>
<p>Python出了不能向后兼容的3.x之后,很多旧版的库都支持不了,而3.x对Unicode的支持让我无法放弃,于是我会比较喜欢能支持3.x的库。</p>
<p>Excel版本支持?</p>
<p>Excel历史悠久,版本众多,但是还好主要可以分为2类,XLS(97-2003)和XLSX(2007+)。</p>
<p>XLS的局限性:最大行数为65535,最大列数为255。</p>
<p>发现</p>
<p>通过几个小时的学习,终于得到了以下几种通过Python第三方库操作Excel文件的方法:</p>
<p>来自Python-Excel的第三方库(xlrd、xlwt、xlutils)</p>
<p>这种方法其实是由三个库组成:</p>
<p>xlrd (Excel Reader): 读</p>
<p>支持Python 2.x和3.x,支持XLS和XLSX文件读取。</p>
<p>xlwt (Excel Writer): 写</p>
<p>仅支持Python 2.x,仅支持写XLS。</p>
<p>但是后来又找到了这个版本的一个支持Python 3.x的fork:xlwt-future,不过还是只支持写XLS。</p>
<p>xlutils: 更多高级操作,依赖前2个库</p>
<p>仅支持Python 2.x。</p>
<p>openpyxl</p>
<p>支持Python 2.x和3.x,仅支持XLSX的读取和写入。</p>
<p>使用</p>
<p>由于xlutils不支持Python 3.x,所以我就直接放弃了,通过xlrd和xlwt来读写和通过openpyxl来读写,用法其实挺相似的,对照文档写并不困难。</p>
<p>这时候就要考虑到效率了,比如同样是打开一个1.5MB的XLSX文件(openpyxl不支持XLS,所以对于XLS就没有选择了,而我只需要能处理XLSX就足够了),如果我需要取每个表的指定行,耗时上有多大差异?粗略地在网上看了一下,似乎大家都推荐了xlrd来读取,而且有人说xlrd的读取速度比openpyxl快很多,但是我的实践中恰好相反。</p>
<p>先上代码,分别使用xlrd和openpyxl从 data.xlsx 读取第一行的内容:</p>
<p>使用xlrd</p>
<p>import xlrd
wb=xlrd.open_workbook(filename='data.xlsx', on_demand=True)
for i in range(wb.nsheets):
ws=wb.sheet_by_index(i)
for j in ws.row(0):
print(j.value)
wb.unload_sheet(i)
使用openpyxl</p>
<p>import openpyxl
wb=openpyxl.load_workbook(filename='data.xlsx', use_iterators=True)
sheetnames=wb.get_sheet_names()
for i in sheetnames:
ws=wb.get_sheet_by_name(i)
it=ws.iter_rows()
for j in next(it):
print(j.value)
由于鄙人比较懒,所以就只比较了一下总时间,打开一个1.5MB有6张表的XLSX文件,第1种方法用时8秒,第2种方法用时1秒,两种方法都是按需加载表格,通过直觉(部分代码未提供)可以发现两种方法的耗时都主要花在打开表格这一步上,也就是说,打开表格后从每个表中读取第一行其实花的时间并不多。而在打开XLSX文件上,xlrd就比openpyxl明显慢了很多。</p>
<p>于是我果断选择了openpyxl,输出的时候遇到一个小插曲:</p>
<p>import openpyxl
wb=openpyxl.Workbook(optimized_write=True)
ws=wb.create_sheet()</p>
<p>for irow in range(100):
ws.append(['%d' % i for i in range(20)])
wb.save(filename='data.xlsx')</p>
<p>这是直接从官方文档里抄来了一个简单例子,顺利地生成了一个 data.xlsx 文件,然后用WPS打开的时候就提示出错了!检查了半天觉得程序应该没错了,于是就怀疑是openpyxl坏掉了?最后抱着试一试的态度,用LibreOffice打开了一下,很正常哇!我用WPS已经很久没遇到过打不开的文件了,所以推测:使用openpyxl生成的XLSX文件虽然符合标准,但可能还是有一些细节和MS Office生成的XLSX文件不同,而WPS的容错能力不够所以就直接报错了,不如去上报一下~</p>
<p>2014-10-31 更新:</p>
<p>WPS个人版更新到9.1.0.4867,再打开这个文件就正常了!</p>
<h3>
<a id="用python读取excelxls文件xlrd模块的使用" class="anchor" href="#%E7%94%A8python%E8%AF%BB%E5%8F%96excelxls%E6%96%87%E4%BB%B6xlrd%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>用Python读取Excel(*.xls)文件——xlrd模块的使用</h3>
<p>简介</p>
<p>xlrd是python的一个第三方模块,可以实现跨平台读Microsoft Excel文件。(它有一个兄弟叫xlwt,专注于写Excel文件。)
它并不像win2com那样借助COM技术来访问Excel,而是直接分析Excel文件格式,从中解析数据。因此你可以在任何支持python的平台上使用excel文件。这一点它比win2com要优秀得多。
另外,它对unicode支持的很好,这也是我青睐它的重要原因。
它的工作原理所限,我们不能期望它覆盖Excel全部的功能,访问到全部的数据。
比如,下面这些数据类型xlrd会忽略掉:</p>
<p>图表,宏,图片等嵌入对象(包括嵌入的worksheet)。
VBA模块。
公式(只能识别公式的计算结果,而不是公式本身)。
注释。
链接。
但一些简单的读取还是得心应手的,这已经能满足大多数情况下的需求。
现在它能支持的Excel版本包括:2004, 2003, XP, 2000, 97, 95, 5.0, 4.0, 3.0, 2.1, 2.0。 官方未说明它是否能支持Excel 2007。
它有两个分支,分别是:</p>
<p>xlrd (<a href="http://pypi.python.org/pypi/xlrd%EF%BC%89">http://pypi.python.org/pypi/xlrd)</a> 针对Python 2.x系列。
xlrd3(<a href="http://pypi.python.org/pypi/xlrd3%EF%BC%89">http://pypi.python.org/pypi/xlrd3)</a> 针对Python 3.x系列。</p>
<p>这两个分支是100%兼容的,也就是说,它们的使用完全一样,你在3.x系列中怎么用xlrd,在2.x系列中仍然这么用。
以下的实际操作都使用xlrd3,在python 3.2下完成。</p>
<p>安装</p>
<p>xlrd在python官网的发布主页是<a href="http://pypi.python.org/pypi/xlrd3">http://pypi.python.org/pypi/xlrd3</a> ,当前xlrd3的最新版本是0.1.4。
下载得到一个压缩包,假设我们将它解压到D:\Download\xlrd3-0.1.4,可以看到如下文件。
可以看到有文档、示例、测试文件等。注意其中的setup.py,它是标准的python模块安装方式。
先确认一下python的版本与xlrd3是否一致。</p>
<p>D:\Download\xlrd3-0.1.4>python -V
Python 3.2.2</p>
<p>OK,我们用的是python3,接下来执行安装脚本。</p>
<p>D:\Download\xlrd3-0.1.4>python setup.py install</p>
<p>一长串输出后,没有看到错误的话,xlrd就安装成功了。</p>
<p>试用</p>
<p>假设我们有一个文件叫test.xls,位于D:\Workspace\Python\xlrd3-test\test.xls
其内容如下:
这是一张9行4列的PC主机报价单,当然,价格全是扯淡。
下面使用xlrd程序将PC这张表的内容打印出来。</p>
<p>01 import xlrd3
02<br>
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<br>
11 # total rows and cols
12 print("%d rows, %d cols"%(mysheet.nrows, mysheet.ncols))
13<br>
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<br>
21 if <strong>name</strong> == '<strong>main</strong>':
22 main()
输出:</p>
<p>大功告成!
以上仅是一个入门介绍,关于xlrd更多的信息请参考:</p>
<p><a href="http://packages.python.org/xlrd3/">http://packages.python.org/xlrd3/</a>
<a href="http://www.lexicon.net/sjmachin/xlrd.htm">http://www.lexicon.net/sjmachin/xlrd.htm</a></p>
<h3>
<a id="python操作excel表格xlrdxlwt" class="anchor" href="#python%E6%93%8D%E4%BD%9Cexcel%E8%A1%A8%E6%A0%BCxlrdxlwt" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>python操作excel表格(xlrd/xlwt)</h3>
<p><a href="http://www.cnblogs.com/zhoujie/p/python18.html">http://www.cnblogs.com/zhoujie/p/python18.html</a></p>
<h3>
<a id="python-excel-tutorial-一xlrd的安装和读取excel文件" class="anchor" href="#python-excel-tutorial-%E4%B8%80xlrd%E7%9A%84%E5%AE%89%E8%A3%85%E5%92%8C%E8%AF%BB%E5%8F%96excel%E6%96%87%E4%BB%B6" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Python Excel Tutorial (一):xlrd的安装和读取Excel文件</h3>
<p><a href="http://huaxia524151.iteye.com/blog/1173828">http://huaxia524151.iteye.com/blog/1173828</a></p>
<footer class="site-footer">
<span class="site-footer-owner"><a href="https://github.com/Qijiang60/python_excel">Python excel</a> is maintained by <a href="https://github.com/Qijiang60">Qijiang60</a>.</span>
<span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a> using the <a href="https://github.com/jasonlong/cayman-theme">Cayman theme</a> by <a href="https://twitter.com/jasonlong">Jason Long</a>.</span>
</footer>
</section>
</body>
</html>