Some data needs to be added to existing excel sheet. Here is the code. It is not working with some errors. I am Mechanical Engineer facing some issues with this code
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")
First load workbook, then load your sheet ( sheet=wb["Sheet1"]
). You can assign the values directly to the cells by accessing using sheet['R1']
. Below code should work.
Please check : (case sensitive) 1. Your path is correct
2. Your excel workbook name is correct &
3. Your sheet name is correct('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")
Edit: you can use the below code to update columns 'R' and 'S' from 2 to 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
will fill the values till the current last row, ie if you have values till 50th row , it will fill till 50th
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.