用python读写excel的方法


Posted in Python onNovember 18, 2014

本文实例讲述了用python读写excel的方法。分享给大家供大家参考。具体如下:

最近需要从多个excel表里面用各种方式整理一些数据,虽然说原来用过java做这类事情,但是由于最近在学python,所以当然就决定用python尝试一下了。发现python果然简洁很多。这里简单记录一下。(由于是用到什么学什么,所以不算太深入,高手勿喷,欢迎指导)

一、读excel表

读excel要用到xlrd模块,官网安装(http://pypi.python.org/pypi/xlrd)。然后就可以跟着里面的例子稍微试一下就知道怎么用了。大概的流程是这样的:

1、导入模块

import xlrd

2、打开Excel文件读取数据

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

3、获取一个工作表

①  table = data.sheets()[0]       #通过索引顺序获取
②  table = data.sheet_by_index(0) #通过索引顺序获取
③  table = data.sheet_by_name(u'Sheet1')#通过名称获取
4、获取整行和整列的值(返回数组)

table.row_values(i)

table.col_values(i)

5、获取行数和列数 
table.nrows

table.ncols

6、获取单元格
table.cell(0,0).value

table.cell(2,3).value

就我自己使用的时候觉得还是获取cell最有用,这就相当于是给了你一个二维数组,余下你就可以想怎么干就怎么干了。得益于这个十分好用的库代码很是简洁。但是还是有若干坑的存在导致话了一定时间探索。现在列出来供后人参考吧:

1、首先就是我的统计是根据姓名统计各个表中的信息的,但是调试发现不同的表中各个名字貌似不能够匹配,开始怀疑过编码问题,不过后来发现是因为

空格。因为在excel中输入的时候很可能会顺手在一些名字后面加上几个空格或是tab键,这样看起来没什么差别,但是程序处理的时候这就是两个完全

不同的串了。我的解决方法是给每个获取的字符串都加上strip()处理一下。效果良好

2、还是字符串的匹配,在判断某个单元格中的字符串(中文)是否等于我所给出的的时候发现无法匹配,并且各种unicode也不太奏效,百度过一些解决

方案,但是都比较复杂或是没用。最后我采用了一个比较变通的方式:直接从excel中获取我想要的值再进行比较,效果是不错就是通用行不太好,个

呢不能问题还没解决。
二、写excel表

写excel表要用到xlwt模块,官网下载(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:

1、导入模块

import xlwt

2、创建workbook(其实就是excel,后来保存一下就行)
workbook = xlwt.Workbook(encoding = 'ascii')

3、创建表
worksheet = workbook.add_sheet('My Worksheet')

4、往单元格内写入内容
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')

5、保存
workbook.save('Excel_Workbook.xls')

由于我的需求比较简单,所以这上面没遇到什么问题,唯一的就是建议还是用ascii编码,不然可能会有一些诡异的现象。

当然xlwt功能远远不止这些,他甚至可以设置各种样式之类的。附上一点例子

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/

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python调用cmd复制文件代码分享
Dec 27 Python
python获取指定网页上所有超链接的方法
Apr 04 Python
python使用str & repr转换字符串
Oct 13 Python
Python如何发布程序的详细教程
Oct 09 Python
python单线程文件传输的实例(C/S)
Feb 13 Python
Python3.4学习笔记之列表、数组操作示例
Mar 01 Python
Python pip替换为阿里源的方法步骤
Jul 02 Python
在Python中COM口的调用方法
Jul 03 Python
Tensorflow中tf.ConfigProto()的用法详解
Feb 06 Python
Python之Matplotlib文字与注释的使用方法
Jun 18 Python
解决阿里云邮件发送不能使用25端口问题
Aug 07 Python
Python Matplotlib绘制两个Y轴图像
Apr 13 Python
kNN算法python实现和简单数字识别的方法
Nov 18 #Python
决策树的python实现方法
Nov 18 #Python
linux 下实现python多版本安装实践
Nov 18 #Python
centos 下面安装python2.7 +pip +mysqld
Nov 18 #Python
朴素贝叶斯算法的python实现方法
Nov 18 #Python
使用django-suit为django 1.7 admin后台添加模板
Nov 18 #Python
DJANGO-ALLAUTH社交用户系统的安装配置
Nov 18 #Python
You might like
url decode problem 解决方法
2011/12/26 PHP
自己写的php curl库实现整站克隆功能
2015/02/12 PHP
php实现兼容2038年后Unix时间戳转换函数
2015/03/18 PHP
PHP文件上传操作实例详解
2016/09/27 PHP
用js实现的一个Flash滚动轮换显示图片代码生成器
2007/03/14 Javascript
在JavaScript中,为什么要尽可能使用局部变量?
2009/04/06 Javascript
有趣的JavaScript数组长度问题代码说明
2011/01/20 Javascript
Function.prototype.bind用法示例
2013/09/16 Javascript
node.js中的events.emitter.once方法使用说明
2014/12/10 Javascript
jQuery使用$.ajax进行即时验证的方法
2015/12/08 Javascript
js获取时间精确到秒(年月日)
2016/03/16 Javascript
JS验证不重复验证码
2017/02/10 Javascript
WebGL three.js学习笔记之阴影与实现物体的动画效果
2019/04/25 Javascript
vue-test-utils初使用详解
2019/05/23 Javascript
JS控制GIF图片的停止与显示
2019/10/24 Javascript
Vue-CLI 3 scp2自动部署项目至服务器的方法
2020/07/24 Javascript
[01:08:57]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS LGD第二场
2014/05/24 DOTA
基于python(urlparse)模板的使用方法总结
2017/10/13 Python
python中map的基本用法示例
2018/09/10 Python
python 求定积分和不定积分示例
2019/11/20 Python
关于win10在tensorflow的安装及在pycharm中运行步骤详解
2020/03/16 Python
Python tkinter界面实现历史天气查询的示例代码
2020/08/23 Python
Android笔试题总结
2014/11/29 面试题
德尔福集团DELPHI的笔试题
2012/02/22 面试题
大学教师年终总结的自我评价
2013/10/29 职场文书
中专三年学习的个人自我评价
2013/12/12 职场文书
工程管理专业毕业生自荐信
2014/01/24 职场文书
火车来了教学反思
2014/02/11 职场文书
2014年社会实践活动总结范文
2014/04/29 职场文书
事业单位考核材料
2014/05/21 职场文书
职业规划实施方案
2014/06/10 职场文书
单位一把手群众路线四风问题整改措施
2014/09/25 职场文书
水电工岗位职责
2015/02/14 职场文书
2015年上半年计生工作总结
2015/03/30 职场文书
放假通知格式
2015/04/14 职场文书
客户付款通知书
2015/04/23 职场文书