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

时间:2016-04-19 19:34:56

标签: excel python-2.7 pandas openpyxl xlutils

我在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文件的方法。请帮帮我,我被困在这里。

1 个答案:

答案 0 :(得分:0)

我多次遇到这个问题,并且无法使用纯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