python写入已存在的excel数据实例

yipeiwu_com6年前Python基础

python可以使用xlrd读excel,使用xlwt写excel,但是如果要把数据写入已存在的excel,需要另外一个库xlutils配合使用.

大概思路:

1、用xlrd.open_workbook打开已有的xsl文件

注意添加参数formatting_info=True,得以保存之前数据的格式

2、然后用,from xlutils.copy import copy;,之后的copy去从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量

3、然后对于xlwt的Workbook变量,就是正常的:

通过get_sheet去获得对应的sheet,拿到sheet变量后,就可以往sheet中,写入新的数据

4、写完新数据后,最终save保存

源码例子:

import xlrd
import os
from xlutils.copy import copy
from xlwt import Style

def writeExcel(row, col, str, styl=Style.default_style):
 rb = xlrd.open_workbook(file, formatting_info=True)
 wb = copy(rb)
 ws = wb.get_sheet(0)
 ws.write(row, col, str, styl)
 wb.save(file)

style = xlwt.easyxf('font:height 240, color-index red, bold on;align: wrap on, vert centre, horiz center');
writeExcel(1, 1, 'hello world', style) 

如果需要excel原格式,需要加参数

formatting_info=True

如果需要加excel样式,传入样式字符串给xlwt.easyxf即可

合并单元格:

ws.write_merge(top_row, bottom_row, left_column, right_column, string)

以上这篇python写入已存在的excel数据实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python获取Linux发行版名称

我必须从Python脚本中获取Linux发行版名称。dist平台模块中有一个方法: import platform platform.dist() 但在我的Arch Linux下...

Python实现的简单模板引擎功能示例

本文实例讲述了Python实现的简单模板引擎功能。分享给大家供大家参考,具体如下: #coding:utf- 8 __author__="sdm" __author_email='s...

Python运行报错UnicodeDecodeError的解决方法

Python2.7在Windows上有一个bug,运行报错: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in...

Python的迭代器和生成器

先说迭代器,对于string、list、dict、tuple等这类容器对象,使用for循环遍历是很方便的。在后台for语句对容器对象调用iter()函数,iter()是python的内置...

python单线程文件传输的实例(C/S)

python单线程文件传输的实例(C/S)

客户端代码: #-*-encoding:utf-8-*- import socket import os import sys import math import time...