如何用Python追加特定Excel单元格值?
单元格(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
试试用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)
0
这是xlwt的默认行为,你可以通过以下方式来覆盖它:
sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)
(这个内容来自于这个回答)不过,这样做只会覆盖原来的值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())