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

最后演示结果图:

最后是官方实例,比较详细,有用到的可以看一下:

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=[[‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘31‘, ‘snidel‘, 81], [‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘69‘, ‘Bout hent ique‘, 12], [‘20160501‘, ‘2016-05-01 10‘, ‘20030‘, ‘95‘, ‘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‘)#打开一个工作薄

实例代码

时间: 2024-10-10 07:31:46

python-操作exel(xlrd,xlwt)的相关文章

【python】操作excel——xlrd xlwt xlutils

from xlutils.copy import copy import xlrd # import xlutils #打开已存在的excel rb=xlrd.open_workbook('D:\\1.xls',formatting_info=True, on_demand=True) rs=rb.sheet_by_index(0).cell(0,0).value #复制 wb=copy(rb) #插入or修改数据 wb.get_sheet(0).write(1,0,'7') #保存(保存的路径

Python操作Excel之xlwt

#写入import xlwtworkbook=xlwt.Workbook()sheetn=workbook.add_sheet(u"测试数据",cell_overwrite_ok=True)sheetn.write(0,0,u"中国")sheetn.write(1,0,u"美国")sheetn.write(2,0,u"德国")style=xlwt.XFStyle()ft=xlwt.Font()ft.name="Tim

自己总结python用xlrd\xlwt读写excel

1.首先安装xlrd\xlwt模块 xlrd模块下载地址: https://pypi.python.org/pypi/xlrd xlwt模块下载地址: https://pypi.python.org/pypi/xlwt linux 安装命令 python setup.py install windos 安装命令 setup.py install 2.使用方法大全 基础方法推荐请看这里: http://blog.csdn.net/mr__fang/article/details/7089581 简

python+xlrd+xlwt操作excel

介绍 xlrd(读操作),xlwt(写操作) 上述软件下载后,分别解压,之后在cmd命令下分别进入对应的目录中运行 python setup.py install 如果运行过程中提示缺少setuptools,则先运行python ez_setup.py之后在重复上面的步骤 PS:office的版本不要用太高的,建议最好用03版本的,且后缀为xls的 源码bug修复 安装好xlwt3后,找到formula.py文件,将其中的 __slots__ = ["__init__", "

Python操作excel的几种方式--xlrd、xlwt、openpyxl

openpyxl xlrd xlwt 在处理excel数据时发现了xlwt的局限性–不能写入超过65535行.256列的数据(因为它只支持Excel 2003及之前的版本,在这些版本的Excel中行数和列数有此限制),这对于实际应用还是不够的.为此经过一番寻找发现了一个支持07/10/13版本Excel的openpyxl,虽然功能很强大,但是操作起来感觉没有xlwt方便.下面分别说下几个模块的常用操作. xlrd xlrd是用来从Excel中读写数据的,但我平常只用它进行读操作,写操作会遇到些问

【转】python操作excel表格(xlrd/xlwt)

[转]python操作excel表格(xlrd/xlwt) 最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异,而且不太能满足需求,不过经过一番对源码的"研究"(用此一词让我觉得颇有成就感)之后,基本解决了日常所需.主要记录使用过程的常见问题及解决. python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库.可从这里下载https://pyp

Python处理Excel文档(xlrd, xlwt, xlutils)

简介 xlrd,xlwt和xlutils是用Python处理Excel文档(*.xls)的高效率工具.其中,xlrd只能读取xls,xlwt只能新建xls(不可以修改),xlutils能将xlrd.Book转为xlwt.Workbook,从而得以在现有xls的基础上修改数据,并创建一个新的xls,实现修改. (以下属性或方法并非全部,需要更多属性请参看文档:建议先参考文末Demo,再深入了解) xlrd Book(class) 由xlrd.open_work("example.xls"

python xlrd xlwt

1.什么是xlrd模块? 2.为什么使用xlrd模块? 3.怎样使用xlrd模块? 1.什么是xlrd模块? ?python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库. 今天就先来说一下xlrd模块: 一.安装xlrd模块 ? 到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境. ?或者在cmd窗口  pip install  xlrd 二.使用介绍 ? 0

python操作Excel读写(使用xlrd和xlrt)

包下载地址:https://pypi.python.org/pypi/xlrd 导入 import xlrd 打开excel data = xlrd.open_workbook('demo.xls') #注意这里的workbook首字母是小写 查看文件中包含sheet的名称 data.sheet_names() 得到第一个工作表,或者通过索引顺序 或 工作表名称 table = data.sheets()[0] table = data.sheet_by_index(0) table = dat