简体   繁体   English

如何在python中使用xlsxwriter将数据写入/更新到现有XLSX工作簿的单元格中

[英]How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

I am able to write into new xlsx workbook using我可以使用写入新的 xlsx 工作簿

import xlsxwriter  
def write_column(csvlist):
    workbook = xlsxwriter.Workbook("filename.xlsx",{'strings_to_numbers': True})
    worksheet = workbook.add_worksheet()
    row = 0
    col = 0
    for i in csvlist:
        worksheet.write(col,row, i)
        col += 1

    workbook.close() 

but couldn't find the way to write in an existing workbook.但找不到在现有工作簿中写入的方法。 Please help me to write/update cells in existing workbook using xlswriter or any alternative.请帮助我使用 xlswriter 或任何替代方法在现有工作簿中编写/更新单元格。

Quote from xlsxwriter module documentation : xlsxwriterxlsxwriter模块文档

This module cannot be used to modify or write to an existing Excel XLSX file.此模块不能用于修改或写入现有的 Excel XLSX 文件。

If you want to modify existing xlsx workbook, consider using openpyxl module.如果要修改现有的xlsx工作簿,请考虑使用openpyxl模块。

See also:也可以看看:

you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name您可以使用此代码打开(test.xlsx)文件并修改A1单元格,然后使用新名称保存

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

Note that openpyxl does not have a large toolbox for manipulating and editing images.请注意,openpyxl 没有用于操作和编辑图像的大型工具箱。 Xlsxwriter has methods for images, but on the other hand cannot import existing worksheets... Xlsxwriter 有图像的方法,但另一方面不能导入现有的工作表......

I have found that this works for rows... I'm sure there's a way to do it for columns...我发现这适用于行......我确定有一种方法可以为列做到这一点......

import openpyxl

oxl = openpyxl.load_workbook('File Loction Here')
xl = oxl.['SheetName']

x=0
col = "A"
row = x

while (row <= 100):
    y = str(row)
    cell = col + row
    xl[cell] = x
    row = row + 1
    x = x + 1

You can do by xlwings as well你也可以通过 xlwings 来做

import xlwings as xw
for book in xlwings.books:
    print(book)

If you have issue with writing into an existing xls file because it is already created you need to put checking part like below:如果您在写入现有 xls 文件时遇到问题,因为它已经创建,您需要像下面这样放置检查部分:

PATH='filename.xlsx'
if os.path.isfile(PATH):
    print "File exists and will be overwrite NOW"
else:
    print "The file is missing, new one is created"

... and here part with the data you want to add ...这里是您要添加的数据的一部分

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

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