python-操作exel(xlrd,xlwt)
1.使用第三方库
python中处理excel表格,常用的库有xlrd(读excel)表、xlwt(写excel)表、openpyxl(可读写excel表)等。 xlrd读数据较大的excel表时效率高于openpyxl,所以我在写脚本时就采用了xlrd和xlwt这两个库。介绍及下载地址为:http://www.python-excel.org/ 这些库文件都没有提供修改现有excel表格内容的功能。一般只能将原excel中的内容读出、做完处理后,再写入一个新的excel文件。
1.安装
pip install xlwt
pip install xlrd
2.使用
1.导入模块
import xlrd #导入模块
2.获取一个工作表的数据
table = data.sheets()[0] #通过索引顺序获取,这个是个地址列表
#[u'\u65e5\u671f', u'\u5c0f\u65f6', u'\u697c\u5c42', u'\u5e97\u94fa\u53f7', u'\u5e97\u94fa\u540d\u79f0', u'\u4eba\u6570']
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取 #获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i) #获取行数和列数
nrows = table.nrows
ncols = table.ncols
#循环行列表数据
for i in range(nrows ):
print table.row_values(i)
#单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value #使用行列索引
cell_A1 = table.row(0)[0].value cell_A2 = table.col(1)[0].value
3.写入数据到一个sheel中
w = xlwt.Workbook()#创建一个写入的exel对象
sheet = w.add_sheet('sheet1')#添加一个sheet页
for i in range(len(buf)):
print buf[i]
sheet.write(i,0,buf[i].decode('utf8'))#写入数据
w.save(outEfile) #将数据写入到保存文件,没有这一步数据在内存中
4.设置格式
创建一个样式对象,对其进行设置,之后应用到exel格式中。样式对象有很多设置,举例常用的几个,一个是字体front设置,一个是边框borders设置,一个是Pattern
style = xlwt.XFStyle() # 初始化样式
创建一个front设置,设置其字体等:
font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'#设置字体
font.bold = bold#设置字体颜色
font.color_index = 4
font.height = height#高度
创建一个borders设置:
borders = xlwt.Borders()#创建一个边框对象
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
borders.bottom_colour=0x3A
创建一个Pattern设置:
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,
应用到样式中:
style.borders = borders
style.font = font
style.pattern = pattern # Add Pattern to Style
最后演示结果图:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAh8AAAB6CAIAAACQmaZGAAAVoklEQVR4nO2dv47cNrvGdR+uzjWcbaIm3bmEr9oAqVQbOReQ4yZFqmn3cwIYsQMDxszsrteWnSCFi/ikCJDCdqd+bkNfoZH0knwlUhLJlxo9PwiGV6M/DynyfURSErP/BxynYEin7HJAlgKQMlm4MAoAAGCzwF0AAAD4B+4CAADAP3AXAAAA/oG7AAAA8A/cBQAAgH/gLgAAAPwDdwEAAOAfuAsAAAD/wF0AAAD4x+4u79+//7Rm3r9/HyEfw/Hp0ydpCYuAflmgX5Yt67e7y7t37wS9YTnv3r2bnTsp8M8//0hLWAT0ywL9smxZv91dyrKUNohFlGU5O3dS4O+//5aWsAjolwX6Zdmyfru7vH37NmDsPzx+9M2/vv8Q8Axv376dnTuDfHxylWlcPfno/zyn0+mvv/4KctyTmorrF4FOEkS/kf+hcj+W/nDXIFT54ZIQIgEBy//pxXX4IhSs/KiZba7xxBL9vLt8/vy5+/+bN2+CRf7fv//uq29/ePzoh+fBTvHpzZs3s3NnEPNavrgOFB3+/PPPAEfVBH98chXKYILo1/P/xXWw6BBFf0BClZ9YSQipnyYgVBGKVH6CXY4l+hl3+fz5M43IAd3lw49ff/P4afNvqHPEcpfTi+sw8e3Dhw/+D2qa4ccnVyvSH9HdI+kPRpjyEy8JYfRzxT1MiiKVn2CXY4l+3V0aa6ER+eHhIVDcf/fvfzWtlqc/fPX1v38PdJaHh4fZuTMIG93C1LU//vjD/0GDxWKTIPojunss/aEIov8ULwnIf4aI7r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6QO9MsC/bJAvyyL3MVl9rAvAAAAwBTQdkkd6JcF+mWBflmW6Ie7pA70ywL9skC/LHCXMbZ8dVMA+mWBflm2rN86eRjcRRjolwX6ZYF+WZa5C74EkzbQLwv0ywL9sqBnbIwtX90UgH5ZoF+WLev/D2tCZxrpeyYaAAAAAElFTkSuQmCC" alt="" />
最后是官方实例,比较详细,有用到的可以看一下:
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/
官方实例
最后是一个小实例,遇到了一个比较坑的东西,我想投机取巧,事前先把样式手动设置好,直接往里面写数据。这时我用到了copy,但是往里面写数据没问题,但是在保存的时候,老是报字符集的问题,这也是python2的一大问题吧。一天我也没解决掉,最后只能先放弃了。
#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'wyf' import ConfigParser
import xlwt
import xlrd
import sys
from xlutils.copy import copy
import sys
import codecs
reload(sys)
sys.setdefaultencoding('utf-8') a=[['', '2016-05-01 10', '', '', 'snidel', 81], ['', '2016-05-01 10', '', '', 'Bout hent ique', 12], ['', '2016-05-01 10', '', '', 'ZARA', 254]] def set_style(name,height,bold=False):
style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 4
font.height = height
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 = borders = xlwt.Borders()
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
borders.bottom_colour=0x3A
style.borders = borders
style.font = font
style.pattern = pattern # Add Pattern to Style
return style def writeXlwt(result,row0,book,sheelName):
worksheet = book.add_sheet(sheelName)#添加一个sheet页
print '*****=',row0
for i in range(len(result)+1):
if i ==0:
for f in range(0,len(row0)):
worksheet.write(0,f,row0[f],set_style('Arial',220,True))
else:
for a in range(len(result[i-1])):
worksheet.row(i).write(a,result[i-1][a]) if __name__ =='__main__':
#book = xlwt.Workbook(encoding = 'utf-8')
oldWb = xlrd.open_workbook('test123.xls',formatting_info=True)
book = copy(oldWb)
setattr(book,'encoding','utf-8')
#book = xlwt.Workbook()
cf = ConfigParser.ConfigParser()#生成一个实例
#with codecs.open('config_dayueche.conf', encoding="utf-8" ) as f:
cf.read("config_dayueche.conf") #读取配置文件
sheelList = cf.sections()
for sheel in sheelList:
row0 = cf.get(sheel,'row0').split(';')
writeXlwt(a,row0,book,sheel)
book.save('test1232.xls')#打开一个工作薄
实例代码
python-操作exel(xlrd,xlwt)的更多相关文章
- 使用Python对Excel表格进行简单的读写操作(xlrd/xlwt)
算是一个小技巧吧,只是进行一些简单的读写操作.让人不爽的是xlrd和xlwt是相对独立的,两个模块的对象不能通用,读写无法连贯操作,只能单独读.单独写,尚不知道如何解决. #①xlrd(读) #cod ...
- python操作excel xlrd和xlwt的使用
最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异,而且不太能满足需求,不过经过一番对源码的"研究&q ...
- python操作excel(xlwt写,xlrd读)基本方法
python操作excle在测试工作中还是很有用的,比如读取测试数据,回写测试结果到excel. 1.安装 pip install xlwt pip install xlrd 2.写excel # 导 ...
- python 模块:xlrd && xlwt
主要来自:http://www.jb51.net/article/60510.htm python读excel--xlrd 这个过程有几个比较麻烦的问题,比如读取日期.读合并单元格内容.下面先看看基本 ...
- python模块之xlrd,xlwt,读写execl(xls,xlsx)
安装xlrd,xlwt pip install xlrd xlwt xlrd读取execl [环境ipython python2.7.5] import xlrd book = xlrd.open_w ...
- 【python】操作excel——xlrd xlwt xlutils
from xlutils.copy import copy import xlrd # import xlutils #打开已存在的excel rb=xlrd.open_workbook('D:\\1 ...
- Python操作Excel之xlwt
#写入import xlwtworkbook=xlwt.Workbook()sheetn=workbook.add_sheet(u"测试数据",cell_overwrite_ok= ...
- Python如何读写Excel文件-使用xlrd/xlwt模块
时间: 2020-08-18 整理: qiyuan 安装和导入 1.模块介绍 在 python 中使用 xlrd/xlwt 和 openpyxl 模块可以对Excel电子表格(xls.xlsx文件)进 ...
- 自己总结python用xlrd\xlwt读写excel
1.首先安装xlrd\xlwt模块 xlrd模块下载地址: https://pypi.python.org/pypi/xlrd xlwt模块下载地址: https://pypi.python.org/ ...
随机推荐
- struts2笔记11-OGNL
1.OGNL Object-Graph Navigation Language,对象-图 导航语言,可以方便的操作struts2值栈对象 2.对象栈操作方法 (1)action普通属性的访问方法 &l ...
- Promise原理 && 简单实现
Promise原理 参考https://github.com/chunpu/promise/blob/master/promise.js 个人认为原博的实现有点问题 在next函数的实现上, 会导致无 ...
- LINQ 联合查询
List<Attachment> imgList = (from a in ZQSDWEBEntities.Attachment ...
- 重新关联bat文件的打开方式为系统默认方式
为什么“BAT”扩展名的默认打开方式:显示出来的居然是“%1”这么一个怪异的东东,具体在什么位置的? c:\windowssystem32\command.com修复bat关联,打开command.c ...
- 论山寨手机与Android 【15】结束语
去年11月,与人讨论山寨版Android智能手机的前景,最初觉得这个问题很容易回答.但是三言两语之后,不仅听者茫然,而且言者自己也意识到条理紊乱,说服力不强.于是决定写几篇文章,把这个问题展开说说.所 ...
- ajax缺点以及解决办法
1.缺少一个没有标准之争.没有back和history的浏览器 Ajax取消了back按钮,即对浏览器后退机制的破坏.后退按钮是一个标准的web站点的重要功能,但是它没法和js进行很好的合作,这 ...
- WIN ERROR:C:\Windows\System32\<LANG_NAME>\mstsc.exe.MUI
Issue: When you upgrade Win7, you may found your remote desktop will not work. You may get following ...
- MATLAB介绍
MATLAB MATLAB[1] 是美国MathWorks公司出品的商业数学软件,用于算法开发.数据可视化.数据分析以及数值计算的高级技术计算语言和交互式环境,主要包括MATLAB和Simulink ...
- Dialog 顶部黑线问题
Dialog 顶部黑线问题 样式如下: [java] view plaincopyprint? <style name="Transparent_Dialog"> &l ...
- mysql主从同步错误解决和Slave_IO_Running: NO
1.出现错误提示. Slave I/O: error connecting to master 'backup@192.168.1.x:3306' - retry-time: 60 retries: ...