简体   繁体   English

如何通过Python将数据写入现有的excel文件表?

[英]How to write a data into an exist sheet of excel file by Python?

I'm looking for a way to write some data into an excel file.我正在寻找一种将一些数据写入 excel 文件的方法。 Then I found xlwt seems can reach my requirement, but I only find the way to add a new sheet.然后我发现xlwt似乎可以达到我的要求,但我只能找到添加新工作表的方法。 for example:例如:

sheet = workbook.add_sheet('test222')

If I hope to enter a value into an exist sheet "test 111", does someone know how to do that?如果我希望在现有表“test 111”中输入一个值,有人知道该怎么做吗?

My sample code:我的示例代码:

import xlwt

def write_report():
    f_value = "500"
    workbook = xlwt.Workbook('D:\\Test.xls')
    sheet = workbook.add_sheet('test222')
    sheet.write(5, 3, f_value)

    workbook.save('D:\\Test.xls')

Thanks a lot.非常感谢。





[Update on 7/31/2018] [7/31/2018 更新]
After I used the method of import openpyxl, I met a weird issue.使用了import openpyxl的方法后,遇到了一个奇怪的问题。 Some borders were disappeared after I write data into the file.将数据写入文件后,一些边框消失了。
Original:原来的: 在此处输入图片说明

After I wrote data into the file:在我将数据写入文件后: 在此处输入图片说明

The border of some fields which have been merged were cleared.一些已合并的字段的边界被清除。 (item A, item B, Category 01 and Category 02) Is it the known issue on openpyxl? (项目 A,项目 B,类别 01 和类别 02)这是 openpyxl 上的已知问题吗?

This is minmal example:这是最小的例子:

import openpyxl

wbkName = 'New.xlsx'
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close

The saving with the explicit name of the workbook seems to be quite important - wbk.save(wbkName) , because only wbk.save does not do the job completely, but does not throw an error.使用工作簿的显式名称保存似乎非常重要 - wbk.save(wbkName) ,因为只有wbk.save不能完全完成工作,但不会引发错误。

You can use xltpl for this - A python module to generate xls/x files from a xls/x template.您可以为此使用xltpl - 从 xls/x 模板生成 xls/x 文件的 python 模块。

Use your excel file as the template.使用您的 excel 文件作为模板。
Put variables in the cells, such as : {{f_value}}, {%xv someValue%}在单元格中放入变量,例如: {{f_value}}, {%xv someValue%}

from xltpl.writer import BookWriter
writer = BookWriter('template.xls')
payload = {"f_value": "500", "someValue": 1337}
payloads = [payload]
writer.render_book(payloads)
writer.save('result.xls')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM