将数据添加到现有的Excel工作表

时间:2019-04-15 06:54:27

标签: python

一些数据需要添加到现有的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")

1 个答案:

答案 0 :(得分:0)

首先加载工作簿,然后加载工作表(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