向现有的Excel文件中写入数据

5
我有一个.xlsx文件,其中有多个工作表(含一些内容)。我想要将一些数据写入特定的sheet1和sheet5。目前我是使用xlrd、xlwt和xlutils copy()函数来实现的。但是是否有一种方法可以以追加模式打开文件并添加数据并保存(像我们对文本/CSV文件所做的那样)呢?
以下是我的代码:
rb = open_workbook("C:\text.xlsx",formatting_info='True')
wb = copy(rb)
Sheet1 = wb.get_sheet(8)
Sheet2 = wb.get_sheet(7)
Sheet1.write(0,8,'Obtained_Value')
Sheet2.write(0,8,'Obtained_Value')
value1 = [1,2,3,4]  
value2 = [5,6,7,8]
for i in range(len(value1)):
 Sheet1.write(i+1,8,value1[i])
for j in range(len(value2)):
 Sheet2.write(j+1,8,value2[j])
wb.save("C:\text.xlsx")
2个回答

9
你可以使用openpyxl模块或者xlwings模块来完成。
  1. Using openpyxl

    from openpyxl import workbook #pip install openpyxl
    from openpyxl import load_workbook
    
    wb = load_workbook("C:\text.xlsx")
    sheets = wb.sheetnames
    Sheet1 = wb[sheets[8]]
    Sheet2 = wb[sheets[7]]
    #Then update as you want it
    Sheet1 .cell(row = 2, column = 4).value = 5 #This will change the cell(2,4) to 4
    wb.save("HERE PUT THE NEW EXCEL PATH") 
    

    the text.xlsx file will be used as a template, all the values from text.xlsx file together with the updated values will be saved in the new file

  2. Using xlwings

     import xlwings 
     wb = xlwings.Book("C:\text.xlsx")  
     Sheet1 = wb.sheets[8]
     Sheet2 = wb.sheets[7]
     #Then update as you want it
     Sheet1.range(2, 4).value = 4 #This will change the cell(2,4) to 4
     wb.save()
     wb.close()
    

    Here the file will be updated in the text.xlsx file but if you want to have a copy of the file you can use the code below

    shutil.copy("C:\text.xlsx", "C:\newFile.xlsx") #copies text.xslx file to newFile.xslx
    

    and use

    wb = xlwings.Book("C:\newFile.xlsx") instead of wb = xlwings.Book("C:\text.xlsx")
    

    As a user of both modules I prefer the second one over the first one.


2
你应该说xlwings只适用于Windows和MacOS。 - debuti

1

要操作现有的Excel文件,您应该使用openpyxl。其他常见的库(如您正在使用的)不支持操作现有的Excel文件。一种解决方法是

  • 将输出文件另存为不同的名称 - text_temp.xlsx
  • 删除原始文件 - text.xlsx
  • 将输出文件的名称更改为text.xlsx - text_temp.xlsx

谢谢您的回复。我了解到openpyxl仅支持.xls文件而不是.xlsx文件。根据您提供的解决方法,您的意思是创建一个新文件,将现有文件的内容和想要添加的新内容保存在其中,然后将其重命名为原始文件,是这样吗? - user3487900
是的。而且 openpyxl 完美支持 xlsx 格式。 - Vikas Ojha
谢谢。我会研究openpyxl库。 - user3487900
你好。openpyxl支持.xls文件吗?我收到以下错误消息:InvalidFileException:openpyxl不支持旧的.xls文件格式,请使用xlrd读取此文件,或将其转换为更近期的.xlsx文件格式。 - user3487900
是的,没错,openpyxl不支持 .xls 文件。 - Vikas Ojha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接