簡體   English   中英

將數據添加到現有Excel工作表

[英]Add data to existing excel sheet

某些數據需要添加到現有的Excel工作表中。 這是代碼。 它沒有處理一些錯誤。 我是機械工程師,面對這段代碼的一些問題

    import openpyxl
    wb = openpyxl.Workbook() 
    from openpyxl import load_workbook, Workbook 

    #Existing exceel sheet

    book_ro=load_workbook("C:\\Users\\Desktop\\Mechanical\\Data\\Wear_sumary.xlsx")
    sheet=wb.get_sheet_by_name("sheet1")

    #Following is the Data that needs to be added to that sheet

    c1 = sheet['R1']   #R1 represents Column R, Row-1
    c1.value = "Average Disp"
    c2 = sheet['R2']   #R1 represents Column R, Row-2
    c2.value = "=AVERAGE(D2:E2)"
    c3 = sheet['S1']   #S1 represents Column S, Row-1
    c3.value = "Gap"
    c4 = sheet['S2']   #S2 represents Column S, Row-2
    c4.value = "=D3/E4"

    wb.save("C:\\Users\\Desktop\\Mechanical_test\\Data\\Wear_summary.xlsx")

首先加載工作簿,然后加載工作表( sheet=wb["Sheet1"] )。 您可以通過使用工作sheet['R1']直接將值分配給單元格。 下面的代碼應該工作。

請檢查:(區分大小寫)1。您的路徑是正確的
2.您的Excel工作簿名稱是正確的
3.您的工作表名稱是否正確('sheet1')

from openpyxl import load_workbook

#Existing exceel sheet
wb = load_workbook("C:\\Users\\Desktop\\Mechanical\\Data\\Wear_summary.xlsx")
# sheet = wb.get_sheet_by_name("sheet1")
sheet = wb["Sheet1"]

sheet['R1'] = "Average Disp"
sheet['R2'] = "=AVERAGE(D2:E2)"
sheet['S1'] = "Gap"
sheet['S2'] = "=D3/E4"

wb.save("C:\\Users\\Desktop\\Mechanical\\Data\\Wear_summary.xlsx")

編輯:您可以使用以下代碼將列'R'和'S'從2更新為24,

from openpyxl import load_workbook
wb = load_workbook("C:\\Users\\Desktop\\Mechanical\\Data\\Wear_summary.xlsx")
sheet=wb["Sheet1"]

sheet['R1'] = "Average Disp"
sheet['S1'] = "Gap"

# for loop will fill values for 'R' and 'S' from row 2 to row 24
for i in range(2,sheet.max_row+1):
        sheet['R{}'.format(i)] = '=AVERAGE(D{}:E{})'.format(i,i)
        sheet['S{}'.format(i)] = '=D{}/E{}'.format(i+1,i+2)

wb.save("C:\\Users\\Desktop\\Mechanical\\Data\\Wear_summary.xlsx")

# please ensure the path, filename and worksheet name are correct

sheet.max_row+1將填充值直到當前最后一行,即如果你有值到第50行,它將填充到第50行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM