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的工作簿变量,正常:
通过get_sheet取得对应的sheet,取得sheet变量,就可以将新的数据写入sheet
4、写好新数据后,最终保存
源代码示例:
#! /usr/糟糕的苗条/env python
#-* -编码: utf-8-* -
导入openpyxl
导入xlwt
来自xlwt导入*
导入xlrd
from xlrd import open_workbook
from xlutils.copy import copy
fromtempfileimporttemporaryfile
#将数据写入不存在的文件
book=工作簿()
sheet1=book.add_sheet(sheet1) )。
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 :\ study auto\ API _ get\ test.xlsx '
工作簿=open _ workbook (file _ path )
#基于sheet索引或名称获取sheet内容:
sheet=workbook.sheet _ by _ index (0) #第一个sheet
#复制在上打开的excel文件
new _ workbook=copy (工作簿)
#从复制的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 (临时文件) ) )