[英]Add data to existing excel sheet
Some data needs to be added to existing excel sheet. 某些数据需要添加到现有的Excel工作表中。 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"]
). 首先加载工作簿,然后加载工作表(
sheet=wb["Sheet1"]
)。 You can assign the values directly to the cells by accessing using sheet['R1']
. 您可以通过使用工作
sheet['R1']
直接将值分配给单元格。 Below code should work. 下面的代码应该工作。
Please check : (case sensitive) 1. Your path is correct 请检查:(区分大小写)1。您的路径是正确的
2. Your excel workbook name is correct & 2.您的Excel工作簿名称是正确的
3. Your sheet name is correct('sheet1') 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")
Edit: you can use the below code to update columns 'R' and 'S' from 2 to 24,
编辑:您可以使用以下代码将列'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
will fill the values till the current last row, ie if you have values till 50th row , it will fill till 50th sheet.max_row+1
将填充值直到当前最后一行,即如果你有值到第50行,它将填充到第50行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.