Exporting to Excel Using Openpyxl – specific rows and columns

Question:

I have tried succesfuly to populate the data in QTableWidget using Pandas.
Now i want to export to specific rows and columns to an existing excel so i will not lose stylesheet and other data from this excel. Please , help me out finding the solution to run it properly.

Goal is to export to excel to specific rows and columns, rows in range from 7 to 30 and columns from 1 to 13 using OpenPyxl to just modify values of an existing excel. I know "appends" means to add whole data table on the bottom of the excel and i don’t know what function to use instead.

  def kalkuacje_exportuj(self):
    columnHeaders = []

    # create column header list
    for j in range(self.ui.tableWidget.model().columnCount()):
        columnHeaders.append(self.ui.tableWidget.horizontalHeaderItem(j).text())

    df = pd.DataFrame(columns=columnHeaders)

    # create dataframe object recordset
    for row in range(self.ui.tableWidget.rowCount()):
        for col in range(self.ui.tableWidget.columnCount()):
            df.at[row, columnHeaders[col]] = self.ui.tableWidget.item(row, col).text()



    from openpyxl import Workbook
    wb = Workbook()
    wb = load_workbook ('OFERTA_SZABLON.xlsx')
    # ws1 = wb.sheetnames()
    ws1 = wb["DETALE wyceniane osobno"]

    # for row in ws1.iter_rows(min_row=7,
    #                 max_row=30,
    #                 min_col=1,
    #                 max_col=13):
    for row in range(7, 30):
        for col in range(1, 13):
            for r in dataframe_to_rows(df, index=False, header=False):
                ws1.append(r)
        # for cell in row:
        #     print(cell)


    wb.save('OFERTA_SZABLON.xlsx')

Answers:

I solved the problem like this:

from openpyxl import Workbook
wb = Workbook()
wb = load_workbook ('OFERTA_SZABLON.xlsx')
# ws1 = wb.sheetnames()
ws1 = wb["DETALE wyceniane osobno"]

# for r in dataframe_to_rows(df, index=False, header=False):
#     ws1.append(r)
offset_row = 5        
offset_col = 0

row = 1
for row_data in dataframe_to_rows(df, index=False, header=False):
    col = 1
    for cell_data in row_data:

        ws1.cell(row + offset_row, col + offset_col, cell_data)

        col += 1

    row += 1



wb.save('OFERTA_SZABLON.xlsx')
Answered By: Sebastian Kasperski

I cannot figure this out for the life of me.
the guy above me has an error with >>> load_workbook (‘OFERTA_SZABLON.xlsx’)
it makes no sense and Workbook.load_workbook(”) isn’t a thing anyways

dataframe_to_rows doesn’t seem to exist either

Answered By: Noomin