Python 修改现有 .xlsx 文件的数据

Python Modify data of existing .xlsx file

我在 python 中有一些代码使用 openpyxl 创建了一个 .xlsx 文件。

但是,当我尝试修改文件时,新数据会注册到文件中,但以前的数据已经消失了。我听说过使用 deepcopy 或 (.copy.copy) 来复制文件的数据,但如何将复制的数据和我当前的编辑粘贴到 .xlsx 文件中?

(*这里缺少一些代码,因为它是一个带有 GUI 的程序,代码太长了)

##############creating######################

try:
    wb_ID = load_workbook('list.xlsx') 
    ws_ID = wb_ID.active
    pass

except EnvironmentError as e:      # OSError or IOError... As FileNotFoundError only exist in Python 3.x version
    print(os.strerror(e.errno)) #use operating system error to define FileNotFoundErrorError
    from openpyxl import Workbook #import Workbook function to create new xlsx (excel) file
    wb_ID = Workbook()
    ws_ID = wb_ID.active
    ws_ID['A1'] = "IC"
    ws_ID.merge_cells('B1:E1')
    ws_ID['B1'] = "Name"
    ws_ID.merge_cells('F1:K1')
    ws_ID['L1'] = "Email"
    ws_ID['M1'] = "Height"
    ws_ID['N1'] = "Gender"
    ws_ID['K1'] = "Bloodtype"
    ws_ID.merge_cells('O1:Q1')
    ws_ID['O1'] = "Default Consultation Day"
    ws_ID.merge_cells('R1:T1')
    ws_ID['R1'] = "Latest Appoinment"
    wb_ID.save("list.xlsx")
    pass
############editing#########################
wb = load_workbook(filename='list.xlsx')
ws = wb.active
last_row = 1
while True:
    last_row += 1
    cellchecker =ws['A'+str(last_row)].value #get the value of the cell
    print(cellchecker)
    print last_row
    if cellchecker is None: #check if cell is empty-->then this row number is the new row
        wb.save('list.xlsx')
        break
    else:
        continue

print(str(last_row)) #convert to string var before passing the var for worksheet function
from openpyxl import Workbook
wb = Workbook() 
ws = wb.active
ws['A'+str(last_row)] = (str(entry_IC.get().strip(' ')))
ws.merge_cells('B'+str(last_row)+':E'+str(last_row))
ws['B'+str(last_row)] = (str(entry_Name.get()))
ws.merge_cells('F'+str(last_row)+':K'+str(last_row))
ws['F'+str(last_row)] = (str(entry_email.get().strip(' ')))
ws['L'+str(last_row)] = (str(entry_Height.get().strip(' ')))
ws['M'+str(last_row)] = gender_selected
ws['N'+str(last_row)] = bloodtype_selected
ws.merge_cells('O'+str(last_row)+':Q'+str(last_row))
ws['O'+str(last_row)] = str(default_selected_day)
ws.merge_cells('R'+str(last_row)+':T'+str(last_row))
today = datetime.date.today() #as u might wonder why i redeclare this var since it already exist, but this is local var for this function only
ws['T'+str(last_row)] = (str(today))

wb.save('list.xlsx')

注意到编辑部分将覆盖现有数据,如 openpyxl 文档中所警告的那样。我真的找不到修改现有 .xlsx 文件的方法。请帮助我,我被困在这里了。

我已经 运行 多次遇到这个问题,但无法使用纯 python 解决它;但是,您可以使用以下代码从 Python 脚本调用 VBA 宏,该宏可用于修改现有的 excel 文件。

这让我想出了创造性的方法来简化工作,这样我就不必实际打开 excel 文件来更新它们,即使数据处理或收集需要 python.

# run excel macro from python
import win32com.client
fn = '//path/filename.xlsm'
xl=win32com.client.Dispatch("Excel.Application")
xl.Application.Visible = True
xl.Workbooks.Open(Filename = fn,ReadOnly = 1)
xl.Application.Run("macroname")
xl=0