Python使用xlwt模块操作Excel的方法详解


Posted in Python onMarch 27, 2018

本文实例讲述了Python使用xlwt模块操作Excel的方法。分享给大家供大家参考,具体如下:

部分摘自官网文档.

模块安装很简单

$ pip install xlwt

先来个简单的例子:

#!/usr/bin/python
#coding=utf-8
# ==============================================================================
#
#    Filename: demo.py
#  Description: excel operat
#    Created: Tue Apr 25 17:10:33 CST 2017
#     Author: Yur
#
# ==============================================================================
import xlwt
# 创建一个workbook 设置编码
workbook = xlwt.Workbook(encoding = 'utf-8')
# 创建一个worksheet
worksheet = workbook.add_sheet('My Worksheet')
# 写入excel
# 参数对应 行, 列, 值
worksheet.write(1,0, label = 'this is test')
# 保存
workbook.save('Excel_test.xls')

运行后 会在当前目录生成一个Excel_test.xls

官方例子:

Python使用xlwt模块操作Excel的方法详解

运行这个例子的时候 报错

Python使用xlwt模块操作Excel的方法详解

自己又写了一个:

#!/usr/bin/python
#coding=utf-8
# ==============================================================================
#
#    Filename: style.py
#  Description: style
#    Created: Thu Apr 27 15:07:53 CST 2017
#     Author: Yur
#
# ==============================================================================
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = 'Times New Roman'
font.bold = True # 黑体
font.underline = True # 下划线
font.italic = True # 斜体字
style.font = font # 设定样式
worksheet.write(0, 0, 'Unformatted value') # 不带样式的写入
worksheet.write(1, 0, 'Formatted value', style) # 带样式的写入
workbook.save('formatting.xls') # 保存文件

效果:

Python使用xlwt模块操作Excel的方法详解

设置单元格宽度:

import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0,'My Cell Contents')
# 设置单元格宽度
worksheet.col(0).width = 3333
workbook.save('cell_width.xls')

输入一个日期到单元格:

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')

向单元格添加一个公式:

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')

向单元格添加一个超链接:

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')

合并列和行:

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')

设置单元格内容的对其方式:

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')

为单元格议添加边框:

# 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
  DASHED虚线
  NO_LINE没有
  THIN实线
# 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')

为单元格设置背景色:

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')

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

Python 相关文章推荐
详解常用查找数据结构及算法(Python实现)
Dec 09 Python
深入理解python对json的操作总结
Jan 05 Python
PyQt5下拉式复选框QComboCheckBox的实例
Jun 25 Python
在Python中使用K-Means聚类和PCA主成分分析进行图像压缩
Apr 10 Python
基于python 凸包问题的解决
Apr 16 Python
python filecmp.dircmp实现递归比对两个目录的方法
May 22 Python
怎么快速自学python
Jun 22 Python
Django REST Swagger实现指定api参数
Jul 07 Python
django form和field具体方法和属性说明
Jul 09 Python
python制作一个简单的gui 数据库查询界面
Nov 19 Python
Python实现树莓派摄像头持续录像并传送到主机的步骤
Nov 30 Python
python3 googletrans超时报错问题及翻译工具优化方案 附源码
Dec 23 Python
Python安装图文教程 Pycharm安装教程
Mar 27 #Python
python 接口返回的json字符串实例
Mar 27 #Python
使用Django和Python创建Json response的方法
Mar 26 #Python
python查询mysql,返回json的实例
Mar 26 #Python
Python发送http请求解析返回json的实例
Mar 26 #Python
Flask 让jsonify返回的json串支持中文显示的方法
Mar 26 #Python
详谈在flask中使用jsonify和json.dumps的区别
Mar 26 #Python
You might like
php cache类代码(php数据缓存类)
2010/04/15 PHP
php实现读取超大文件的方法
2014/07/28 PHP
详谈phpAdmin修改密码后拒绝访问的问题
2017/04/03 PHP
解决php-fpm.service not found问题的办法
2017/06/06 PHP
extjs DataReader、JsonReader、XmlReader的构造方法
2009/11/07 Javascript
IE bug table元素的innerHTML
2010/01/11 Javascript
jQuery实现单行文字间歇向上滚动源代码
2013/06/02 Javascript
js定时器怎么写?就是在特定时间执行某段程序
2013/10/11 Javascript
JavaScript返回当前会话cookie全部键值对照的方法
2015/04/03 Javascript
javascript操作表格排序实例分析
2015/05/06 Javascript
JavaScript中的getTimezoneOffset()方法使用详解
2015/06/10 Javascript
Jquery中.bind()、.live()、.delegate()和.on()之间的区别详解
2017/08/01 jQuery
js构造函数创建对象是否加new问题
2018/01/22 Javascript
Node.js创建HTTP文件服务器的使用示例
2018/05/11 Javascript
Swiper 4.x 使用方法(移动端网站的内容触摸滑动)
2018/05/17 Javascript
js取0-9随机取4个数不重复的数字代码实例
2019/03/27 Javascript
python发送邮件的实例代码(支持html、图片、附件)
2013/03/04 Python
简单介绍Python中的round()方法
2015/05/15 Python
Python中防止sql注入的方法详解
2017/02/25 Python
Python基于matplotlib绘制栈式直方图的方法示例
2017/08/09 Python
Python使用django框架实现多人在线匿名聊天的小程序
2017/11/29 Python
浅谈python装饰器探究与参数的领取
2017/12/01 Python
python: 判断tuple、list、dict是否为空的方法
2018/10/22 Python
Python如何使用turtle库绘制图形
2020/02/26 Python
Django用数据库表反向生成models类知识点详解
2020/03/25 Python
使用ITK-SNAP进行抠图操作并保存mask的实例
2020/07/01 Python
浅谈matplotlib 绘制梯度下降求解过程
2020/07/12 Python
python 6种方法实现单例模式
2020/12/15 Python
用CSS3来实现社交分享按钮
2014/11/11 HTML / CSS
美国女性卫生用品公司:Thinx
2017/06/30 全球购物
意大利男装网店:Vrients
2019/05/02 全球购物
党代会心得体会
2014/09/04 职场文书
优秀共产党员推荐材料
2014/12/18 职场文书
出纳工作检讨书范文
2014/12/27 职场文书
Mysql 如何批量插入数据
2021/04/06 MySQL
Java GUI编程菜单组件实例详解
2022/04/07 Java/Android