使用 xlwt 写入现有工作簿 [英] writing to existing workbook using xlwt

查看:104
本文介绍了使用 xlwt 写入现有工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到使用 xlwt 写入现有文件的示例.我有一个需要写入的现有 xls 文件.当我使用 xlrd 读取文件时,我似乎无法弄清楚如何将返回的Book"类型转换为 xlwt.Workbook.如果有人能给我举个例子,我将不胜感激.

I am unable to find examples where xlwt is used to write into existing files. I have a existing xls file that I need to write to. When I use xlrd to read the file, I cant seem to figure out how to transform the "Book" type returned into a xlwt.Workbook. I would appreciate if someone can point me to an example.

推荐答案

这是我最近用来做这件事的一些示例代码.

Here's some sample code I used recently to do just that.

它打开一个工作簿,向下移动行,如果满足条件,它会在行中写入一些数据.最后保存修改后的文件.

It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.

from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd

START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3

rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy

for row_index in range(START_ROW, r_sheet.nrows):
    age_nov = r_sheet.cell(row_index, col_age_november).value
    if age_nov == 3:
        #If 3, then Combo I 3-4 year old  for both summer1 and fall1
        w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
        w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')

wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])

这篇关于使用 xlwt 写入现有工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆