how to append data using openpyxl python to excel file from a specified row?

前端 未结 4 660
心在旅途
心在旅途 2020-12-28 23:32

I have different Python list variables(data1, data2, data3 ect) containing data which I want to put into an already existing excel sheet. Presently My loop goes like this.

相关标签:
4条回答
  • 2020-12-28 23:56

    You can use the append() method to append values to the existing excel files. Example:

    workbook_obj = openpyxl.load_workbook(excelFilePath)
    sheet_obj = workbook_obj.active
    col1 = 'NewValueCol1'
    col2 = 'NewValueCol2'
    sheet_obj.append([col1, col2])
    workbook_obj.save(excelFilePath)
    

    here the col1 and col2 values will be added with the existing data in the excel sheet.

    0 讨论(0)
  • 2020-12-29 00:03

    ws.append() will always add rows below any existing data.

    0 讨论(0)
  • 2020-12-29 00:09

    Try using

    sheet.max_row 
    

    it will return the last row value, You can start writing the new values from here.

    max = ws.max_row
    for row, entry in enumerate(data1,start=1):
       st.cell(row=row+max, column=1, value=entry)
    

    Hope it helps.Happy Coding :)

    0 讨论(0)
  • 2020-12-29 00:20

    openpyxl has many different methods to be precise but ws.append in previous answers is strong enough to answer your demands. Consider you have written your data to a new sample.xlsx:

    from openpyxl.workbook import Workbook
    
    headers       = ['Company','Address','Tel','Web']
    workbook_name = 'sample.xlsx'
    wb = Workbook()
    page = wb.active
    page.title = 'companies'
    page.append(headers) # write the headers to the first line
    
    # Data to write:
    companies = [['name1','address1','tel1','web1'], ['name2','address2','tel2','web2']]
    
    for info in companies:
        page.append(info)
    wb.save(filename = workbook_name)
    

    Now, to append new lines you must first open an existing book with load_workbook:

    from openpyxl import load_workbook
    
    workbook_name = 'sample.xlsx'
    wb = load_workbook(workbook_name)
    page = wb.active
    
    # New data to write:
    new_companies = [['name3','address3','tel3','web3'], ['name4','address4','tel4','web4']]
    
    for info in new_companies:
        page.append(info)
    
    wb.save(filename=workbook_name)
    
    0 讨论(0)
提交回复
热议问题