python 将数据写入excel

摘要链接:

python第三方库——xlrd和xlwt操作Excel文件学习 :http://blog.csdn.net/wangkai_123456/article/details/50457284

python操作Excel读写(使用xlrd和xlrt) : http://blog.csdn.net/mr__fang/article/details/7089581

Python中一般使用xlrd(excel read)来读取Excel文件,使用xlwt(excel write)来生成Excel文件(可以控制Excel中单元格的格式),需要注意的是,用xlrd读取excel是不能对其进行操作的:xlrd.open_workbook()方法返回xlrd.Book类型,是只读的,不能对其进行操作。而xlwt.Workbook()返回的xlwt.Workbook类型的save(filepath)方法可以保存excel文件。

因此对于读取和生成Excel文件都非常容易处理,但是对于已经存在的Excel文件进行修改就比较麻烦了。不过,还有一个xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已。

xlutils.copy模块的copy()方法实现了这个功能,示例代码如下:

from xlrd import open_workbook
from xlutils.copy import copy
 
rb = open_workbook('m:\1.xls')
 
#通过sheet_by_index()获取的sheet没有write()方法
rs = rb.sheet_by_index(0)
 
wb = copy(rb)
 
#通过get_sheet()获取的sheet有write()方法
ws = wb.get_sheet(0)
ws.write(0, 0, 'changed!')
 
wb.save('m:\1.xls')

练习代码(通过xlrd 读取 & 写入,再借用copy进行保存):

特别注意:由于copy保存实质上是通过xlwt进行保存的,而实际上xlwt保存的文件。

       而通过xlwt只能写入xls文件,不能写入xlsx文件。

import xlrd
from xlwt import *
from xlutils.copy import copy

xlsfile = 'test.xls'
book = xlrd.open_workbook(xlsfile)

sheet_name = book.sheet_names()
print(sheet_name)

sheet = book.sheet_by_index(1)
nrows = sheet.nrows
ncols = sheet.ncols
print(nrows)
print(ncols)

row_data = sheet.row_values(0)
col_data = sheet.col_values(0)
print(row_data)
print(col_data)

cell_value = sheet.cell_value(3,0)
print(cell_value)
cell_value2 = sheet.cell(3,0)
print(cell_value2)

sheet.put_cell(1,2,1,"test",0)
cell_value2 = sheet.cell(1,1)
print(cell_value2)

#保存xlsfile
wb = copy(book)
wb.save(xlsfile)
原文地址:https://www.cnblogs.com/liuyang92/p/7492336.html