python写入excel(已存在/不存在)

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保存

源码例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import openpyxl
import xlwt
from xlwt import *
import xlrd
from xlrd import open_workbook
from xlutils.copy import copy
from tempfile import TemporaryFile

#向不存在的文件写入数据
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
sheet1.write(0,0,'A1')
sheet1.write(0,1,'B1')

row1 = sheet1.row(1)
row1.write(0,'A2')
row1.write(1,'B2')

#向已存在的文件中写入数据
#打开文件
file_path = "F:\\studyauto\\api_get\\test.xlsx"
workbook = open_workbook(file_path)
#获取sheet内容:根据sheet索引或者名称
sheet = workbook.sheet_by_index(0) #第一个sheet
#复制上面打开的excel文件
new_workbook = copy(workbook)
#从复制的excel文件中,得到写入用列的sheet表,这里写入第一个表即为0
new_sheet = new_workbook.get_sheet(0)
#写入内容
new_sheet.write(0,1,'10')
#保存文件
book.save('simple2.xls')
new_workbook.save(file_path)
book.save(TemporaryFile())

posted @ 2017-08-28 17:43  lindamo  阅读(2275)  评论(1编辑  收藏  举报