---
title: "【转】使用Python操作XLS文件"
author: "doujiu"
date: "2010-03-31T09:42:00Z"
tags: []
slug: "python-xls"
draft: false
lastmod: "2010-03-31T09:42:00Z"
id: 629965
url: "https://doujiu.iteye.com/blog/629965"
---

有一次TE需要一个\*\*信息列表，我用python导出了一个txt文件丢给了他们，结果他们很不悦哇，呵呵，因为他们要把几百项数据人肉到xls文件中 作为列表输出，工作量太大，便要求我导出成xls文件然后再给他们，我以编程实现太难推脱了，今天看了下python操作excle的方法，发现相当简 单，呃，苦了TE们……

      我在网上找了下，发现至少有两种方法，第一种是直接操作excle的com库，当然python自带的lib里面已经给我们封装好了实现，直接使用就可以 了，win32com.client，这种方法甚至可以直接把excle的进程调用起来。用法很简单，网上的文章也汗牛充栋，就不详细解说了，给个小例子 吧，嘻嘻。这种只能在windows下运行，并且需要安装MS Excel。

[view plain](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[copy to clipboard](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[print](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[?](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)

01. # -\*- coding: utf-8 -\*-
02. from win32com.client import constants, Dispatch
03. xlsApp = Dispatch("Excel.Application")
04. # 通过赋值Visible为True或者False可以控制是否 调出excle
05. xlsApp.Visible = 1
06. # xlsBook = xlsApp.Workbooks.Open("c:\\\\magictong.xls")
07. # xlsSht = xlsBook.Worksheets("sheet1")
08. xlsBook = xlsApp.Workbooks.Add()
09. xlsSht = xlsBook.Sheets.Add()
10. xlsSht.Cells(2, 3).Value = "Tecent QQ"
11. xlsSht.Cells(2, 3).Font.Color = 0xff0000
12. xlsSht.Name = "GCD go to bell"
13. xlsBook.SaveAs("c:\\\\magictong.xls")
14. xlsApp.Quit()
15. print "\_\_end"

      第二种方法是使用pyExcelerator开源库，这个可以到[http://sourceforge.net/projects/pyexcelerator/](http://sourceforge.net/projects/pyexcelerator/)去 下载，不过这个链接不是很好下，另外我传了一份到csdn上面也可以去下，比较稳定，[http://d.download.csdn.net/down/1884158/magictong](http://d.download.csdn.net/down/1884158/magictong)。 是一个zip包，解压后的文件如下：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/magictong/EntryImages/20091208/1.jpg)

      examples目录是给出的很多小例子，很全面，把这些例子搞明白，基本上使用pyExcelerator的基本方法你也就全搞明白了，其他目录不用管 了，tools目录里面是一些转换工具，从xls文件转换到txt啦，html啦，有兴趣也可以看看。下面说怎么安装吧，其实readme.txt里面已 经说的很清楚了，仔细看下这个文件吧，嘿嘿，这个目录下还有一个setup.py文件，这个文件是用于库的安装的，安装方法是python setup.py install，在win32下直接写个bat文件把这句写进去，放在和setup.py同一级目录，直接运行就over了，里面有cmd.bat文件是 我加在里面的。

      安装好了，咱们就开始使用吧，先看看解析xls文件，简单几句就搞定了：

[view plain](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[copy to clipboard](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[print](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[?](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)

1. from pyExcelerator import *
2. sheets = parse\_xls("c:/a.xls")
3. print sheets

      xls的源文件如下所示：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/magictong/EntryImages/20091208/2.jpg)

      输出可不简单：

[view plain](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[copy to clipboard](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[print](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[?](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)

1. \[(u'Sheet1', {(0, 1): 1.0, (7, 3): 10.890000000000001, (0, 0): u'tonglei', (1, 1): u'qq', (2, 2): u'\\u7acb\\u91cc\\u4e09\\u77f3', (0, 3): 5.0, (0, 2): 2.0}), (u'Sheet2', {}), (u'Sheet3', {})]

      仔细研究下这个数据，最外层是一个list，里面有三个元组，对应三个sheet，每个元组有两项数据，第一个是sheet的名字，如"Sheet1"， 第二项是一个字典，字典中的每一项的key是一个以xls文件的行列两项为元素的元组，而value就是该行列对应的数值，不过这个里面的类型可能就不会 像xls里面那么丰富了。得到了这些数据，能干什么……我就不说了。

      再看看怎么写xls文件：

[view plain](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[copy to clipboard](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[print](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[?](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)

01. # -\*- coding: cp936 -\*-
02. from pyExcelerator import *
03. # 创建一个工作表
04. w = Workbook()
05. # 增加一个sheet并设定名称
06. ws = w.add\_sheet(u"中文的sheet")
07. # 设置样式
08. font0 = Font()
09. font0.name = 'Times New Roman'
10. font0.struck\_out = True
11. font0.bold = True
12. style0 = XFStyle()
13. style0.font = font0
14. ws.write(1, 1, u"magictong", style0)
15. ws.write(1, 2, 45)
16. # 我想写一个数值
17. style1 = XFStyle()
18. style1.num\_format\_str = "0"
19. ws.write(2, 4, 12, style1)
20. ws.write(2, 5, 4, style1)
21. # 保存
22. w.save("c:\\\\mini.xls")

      输出xls文件如下：

 ![](http://p.blog.csdn.net/images/p_blog_csdn_net/magictong/EntryImages/20091208/3.jpg)

      输出格式是很多的，可以看一个自带的例子：

[view plain](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[copy to clipboard](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[print](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)[?](http://blog.csdn.net/magictong/archive/2009/12/08/4966822.aspx)

01. #!/usr/bin/env python
02. # -\*- coding: windows-1251 -\*-
03. # Copyright (C) 2005 Kiseliov Roman
04. \_\_rev\_id\__ = """$Id: num\_formats.py,v 1.1 2005/07/20 07:24:11 rvk Exp $"""
05. from pyExcelerator import *
06. w = Workbook()
07. ws = w.add\_sheet('Hey, Dude')
08. fmts = [
09. 'general',
10. '0',
11. '0.00',
12. '#,##0',
13. '#,##0.00',
14. '"$"#,##0\_);("$"#,##',
15. '"$"#,##0\_);\[Red]("$"#,##',
16. '"$"#,##0.00\_);("$"#,##',
17. '"$"#,##0.00\_);\[Red]("$"#,##',
18. '0%',
19. '0.00%',
20. '0.00E+00',
21. '# ?/?',
22. '# ??/??',
23. 'M/D/YY',
24. 'D-MMM-YY',
25. 'D-MMM',
26. 'MMM-YY',
27. 'h:mm AM/PM',
28. 'h:mm:ss AM/PM',
29. 'h:mm',
30. 'h:mm:ss',
31. 'M/D/YY h:mm',
32. '\_(#,##0\_);(#,##0)',
33. '\_(#,##0\_);\[Red](#,##0)',
34. '\_(#,##0.00\_);(#,##0.00)',
35. '\_(#,##0.00\_);\[Red](#,##0.00)',
36. '\_("$"* #,##0\_);\_("$"* (#,##0);\_("$"* "-"\_);\_(@\_)',
37. '\_(* #,##0\_);\_(* (#,##0);\_(* "-"\_);\_(@\_)',
38. '\_("$"* #,##0.00\_);\_("$"* (#,##0.00);\_("$"* "-"??\_);\_(@\_)',
39. '\_(* #,##0.00\_);\_(* (#,##0.00);\_(* "-"??\_);\_(@\_)',
40. 'mm:ss',
41. '\[h]:mm:ss',
42. 'mm:ss.0',
43. '##0.0E+0',
44. '@'
45. ]
46. i = 0
47. for fmt in fmts:
48. ws.write(i, 0, fmt)
49. style = XFStyle()
50. style.num\_format\_str = fmt
51. ws.write(i, 4, -1278.9078, style)
52. i += 1
53. w.save('num\_formats.xls')

       可以运行一下，看看都有些什么格式的可以输出，不过我找了下，不知道怎么输出一个标准的数值。

![](http://img.zemanta.com/pixy.gif?x-id=60fb1e85-adbb-80ef-be57-bf6732b378b0)