使用Python对Excel表格进行简单的读写操作(xlrd/xlwt)
算是一个小技巧吧,只是进行一些简单的读写操作。让人不爽的是xlrd和xlwt是相对独立的,两个模块的对象不能通用,读写无法连贯操作,只能单独读、单独写,尚不知道如何解决。
#①xlrd(读)
#coding:utf-8
import xlrd
data = xlrd.open_workbook("test.xls")#打开test.xls
names = data.sheet_names() #获取xls文件中所有sheet的名称
table1 = data.sheets()[0] #获取xls文件的第一个工作表
table2 = data.sheet_by_index(0) #通过索引获取xls文件第0个工作表
table3 = data.sheet_by_name(u'Sheet1') #通过工作表名获取工作表
#获取相应工作表的行数和列数
nrows = table1.nrows #获取行数
ncols = table1.ncols #获取列数
#获取整行和整列的值(返回列表对象)
val1 = table1.row_values(0) #获取第1行的数据
val2 = table1.col_values(0) #获取第1列的数据
print val1
#循环行,获得索引的列表
for row in range(table1.nrows):
print table1.row_values(row)
#获取指定单元格的值
cell_A1 = table1.cell(0,0).value
#分别使用行列索引
cell_A1 = table1.row(0)[0].value
cell_A2 = table1.col(1)[0].value
#简单的写入(不知道为什么没办法保存到文件)
row = 0
col = 0
ctype = 1 #类型 0 空,1 字符串,2 数字,3 日期,4 布尔,5 错误
value = '王Tacey'
xf = 0 #扩展的格式化(默认是0)
table1.put_cell(row,col,ctype,value,xf)
print table1.cell(0,0)
print table1.cell(0,0).ctype #返回1,代表文本类型
print table1.cell(0,0).value.decode("UTF-8") #str类型,使用decode是为了显示中文
#②xlwt(写)
import xlwt
file = xlwt.Workbook()
table = file.add_sheet("sheet name") #新建一个工作表
table.write(0,0,u'赵钱孙李')
#overwrite_ok=True --->允许单元格重复操作
table = file.add_sheet("ttttt",cell_overwrite_ok = True)
file.save("demo.xls") #保存文件
#使用样式
style = xlwt.XFStyle() #初始化样式
font = xlwt.Font #为样式创建字体
font.name = "Times New Roman"
font.height = 10
font.bold = True #是否加粗
style.font = font #为样式设置字体
table.write(0,2,"bold times text",style)
file.save("demo.xls") #保存文件(出错)
有点小兴奋,有点小失望。
附:
①Python 使用 Xlrd/xlwt 操作 Excelhttp://liluo.org/blog/2011/01/python-using-xlrd-xlwt-operate-excel/
②Python的Excel操作方式的对比http://www.gocalf.com/blog/python-read-write-excel.html
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/
http://www.youlikeprogramming.com/2011/04/examples-generating-excel-documents-using-pythons-xlwt/
使用Python对Excel表格进行简单的读写操作(xlrd/xlwt)的更多相关文章
- 使用Python处理Excel表格的简单方法
使用Python处理Excel表格的简单方法 这篇文章主要介绍了使用Python处理Excel表格的简单方法,本文给大家介绍的非常详细,需要的朋友可以参考下 Excel 中的每一个单元,都会有这些属性 ...
- 【Python】excel读写操作 xlrd & xlwt
xlrd ■ xlrd xlrd模块用于读取excel文件内容 基本用法: workbook = xlrd.open_workbook('文件路径') workbook.sheet_names() # ...
- python 处理 Excel 表格
see: http://www.cnblogs.com/sunada2005/p/3193300.html 一.可使用的第三方库 python中处理excel表格,常用的库有xlrd(读excel)表 ...
- python 对Excel表格的写入
python对Excel表格写入需要导入xlrd ,和xlutils两个库 from xlrd import open_workbook from xlutils.copy import copy o ...
- 通过Python将Excel表格信息导入数据库
前言 公司原采用Excel表格方式记录着服务器资产信息,随着业务的增加,相应的硬件资产也增加,同时物理机虚拟化出多台虚拟机,存在表格管理杂乱.变更资产信息不能及时相互同步, 为了紧跟时代的步伐,老大搞 ...
- python读取Excel表格文件
python读取Excel表格文件,例如获取这个文件的数据 python读取Excel表格文件,需要如下步骤: 1.安装Excel读取数据的库-----xlrd 直接pip install xlrd安 ...
- Python读取Excel表格
前言:需要进行自动化办公或者自动化测试的朋友,可以了解下此文,掌握Python读取Excel表格的方法. 一.准备工作: 1.安装Python3.7.0(官网下载安装包) 2.安装Pycharm(官网 ...
- Python用Pillow(PIL)进行简单的图像操作
Python用Pillow(PIL)进行简单的图像操作 颜色与RGBA值 计算机通常将图像表示为RGB值,或者再加上alpha值(通透度,透明度),称为RGBA值.在Pillow中,RGBA的值表示为 ...
- berkerly db 中简单的读写操作(有一些C的 还有一些C++的)
最近在倒腾BDB,才发现自己确实在C++这一块能力很弱,看了一天的api文档,总算是把BDB的一些api之间的关系理清了,希望初学者要理清数据库基本知识中的环境,句柄,游标的基本概念,这样有助于你更好 ...
随机推荐
- Sensor(GYROSCOPE)
package com.example.sensor01; import java.util.List; import android.hardware.Sensor; import android. ...
- WPF,Silverlight与XAML读书笔记第四十七 - Silverlight与浏览器
说明:本系列基本上是<WPF揭秘>的读书笔记.在结构安排与文章内容上参照<WPF揭秘>的编排,对内容进行了总结并加入一些个人理解. 这部分内容主要介绍Silverlight与浏 ...
- 《C#图解教程》读书笔记之四:类和继承
本篇已收录至<C#图解教程>读书笔记目录贴,点击访问该目录可获取更多内容. 一.万物之宗:Object (1)除了特殊的Object类,其他所有类都是派生类,即使他们没有显示基类定义. ( ...
- 《你必须知道的.NET》读书笔记一:小OO有大智慧
此篇已收录至<你必须知道的.Net>读书笔记目录贴,点击访问该目录可以获取更多内容. 一.对象 (1)出生:系统首先会在内存中分配一定的存储空间,然后初始化其附加成员,调用构造函数执行初 ...
- jQuery弹出层插件popbox
都什么年代了,还自己写弹出层插件!是的,①自己写的自己好控制②可定制性高③兼容低版本IE 本插件有以下特性: 样式分离,可定制,纯净无图片 可自定义按钮及按钮的样式.点击事件 可指定选择器选择页面元素 ...
- Windows UDP socket recvfrom返回10054错误的解决办法
现象: 在Windows 7系统上,A使用UDP socket,调用sendto函数向一个目标地址B发送数据,但是目标地址B没有接收数据,如果A此时立即调用recvfrom试图接收目标地址B发回的数据 ...
- 了解了这些才能开始发挥jQuery的威力
由于当前jQuery如此的如雷贯耳,相信不用介绍什么是jQuery了,公司代码中广泛应用了jQuery,但我在看一些小朋友的代码时发现一个问题,小朋友们使用的仅仅是jQuery的皮毛,只是使用id选择 ...
- [HIMCM暑期班]第3课:一个博弈问题
在一个街道平面图上,住着n个住户.有两个贩卖热狗的商贩,各自想要在街区里摆设一个小摊.每天住户都会去离他家50米范围内的最近的摊点消费.问: 1. 如果两位小贩摆设小摊的顺序有先后(设A先摆,然后B再 ...
- Oracle日期语言修改
-- value带有两个参数,第一个指下限,第二个指上限,将会生成下限到上限之间的数字,但不包含上限.select ceil(dbms_random.value(1000,9999)) from du ...
- Redis学习笔记~StackExchange.Redis实现分布式Session
回到目录 对于多WEB的环境现在已经是必须的了,很难想像一台WEB服务器面对百万并发的响应,所以,我们需要多台WEB服务器集群合作,来缓解这种高并发,高吞吐的场景,而对于多WEB的场景又会有个问题出现 ...