如何使用python追加特定的excel单元格值?

时间:2014-06-18 11:36:54

标签: python excel xlwt xlutils

cell(1,1)应该“把我放在同一个单元格中”:

import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1')
sheet.write(1, 1, "Put me")
n=10
if n>0: 
    sheet.write(1, 1, "in same cell")

2 个答案:

答案 0 :(得分:0)

这是默认的xlwt行为,您可以使用

覆盖它
sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)

(摘自this answer) 但是,这只会覆盖原始值Put me

您必须手动合并这些值,如下所示:

from cStringIO import StringIO

sheet = book.add_sheet('Sheet1')
buf = StringIO()
buf.write('Put me')
if some_condition:
   buf.write(' in same cell')

sheet.write(1, 1, buf.getvalue())

答案 1 :(得分:0)

尝试openpyxl,这对我有用:

from openpyxl import Workbook


def append_to_cell(location,text,sheet):
    new = sheet.cell(location).value+text
    sheet.cell(location).value=new

    return 

file_name='example.xlsx'
cell='A1'
wb = Workbook()
ws = wb.create_sheet()
ws.title = 'test Sheet'
ws.cell(cell).value = 'write this '
append_to_cell(cell,'in same cell',ws)
wb.save(filename=file_name)