python通过openpyxl生成Excel文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了python通过openpyxl生成Excel文件的方法。分享给大家供大家参考。具体如下:

使用前请先安装openpyxl:

easy_install openpyxl

通过这个模块可以很方便的导出数据到Excel

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
from openpyxl.style import Color, Fill
from openpyxl.cell import Cell
#新建一个workbook
wb = Workbook()
#第一个sheet是ws
ws = wb.worksheets[0]
#设置ws的名称
ws.title = u"下单统计"
#给A1赋值
ws.cell('A1').value = '%s'%("跟随总数")
#给A2赋值
#先把数字转换成字母
col = get_column_letter(1)
#赋值
ws.cell('%s%s'%(col, 2)).value = '%s' % ("A2“)  
#字体修改样式
##颜色
ws.cell('A2').style.font.color.index =Color.GREEN
##字体名称
ws.cell('A2').style.font.name ='Arial'
##字号
ws.cell('A2').style.font.size =8
##加粗
ws.cell('A2').style.font.bold =True
##不知道干啥用的
ws.cell('A2').style.alignment.wrap_text =True
##背景 好像不太好用 是个BUG
ws.cell('A2').style.fill.fill_type =Fill.FILL_SOLID
ws.cell('A2').style.fill.start_color.index =Color.DARKRED
##修改某一列宽度
ws.column_dimensions["C"].width =60.0
##增加一个表
ws = wb.create_sheet()
ws.title = u'结单统计'
##保存生成xml
file_name = 'test.xlsx'
file_dir = '/home/x/'
dest_filename = '%s%s'%(file_dir,file_name)
ew = ExcelWriter(workbook = wb)
ew = ExcelWriter(workbook = wb)

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

相关文章

Python的垃圾回收机制详解

引用计数 在Python源码中,每一个对象都是一个结构体表示,都有一个计数字段。 typedef struct_object { int ob_refcnt; struct...

Python生成密码库功能示例

本文实例讲述了Python生成密码库功能。分享给大家供大家参考,具体如下: 这个代码是将字符的所有组合添加到一个文件中,可以设置密码的最大长度,我这里设置的是8位,但是要有心里准备,生成...

python NumPy ndarray二维数组 按照行列求平均实例

我就废话不多说了,直接上代码吧! c = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]) print(c.mean(axi...

python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)

复制代码 代码如下:#-*- coding:utf-8 -*- from win32com.client import Dispatch import time def start_of...

解决yum对python依赖版本问题

错误 # yum list File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: ^ Synt...