简体   繁体   中英

how to save qtablewidget data into excel file using openpyxl

I have a qtablewidet that has data and when the user clicks the export button a dialog will appear asking for filename to save as excel, how do i do that using openpyxl?

here is my code

self.exportbtn.clicked.connect(self.export)

    def export(self):
        try:
            filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '','Excel files(*.xlsx)')
            wb = Workbook()
            sheet = wb.active
            for column in range(self.tableWidget.columnCount()):
                for row in range(self.tableWidget.rowCount()):
                    try:
                        text = str(self.tableWidget.item(row, column).text())
                        sheet.write(row, column, text)
                        wb.save(filename)
                    except Exception as e:
                        print("Error Writing file.")
        except Exception as e:
            print("Error Saving file.")

when i try to click save from the dialog, the output right now is this

在此处输入图像描述

how do i save the whole data including the headers from qtablewidget to an excel file using openpyxl?

update: i edited my code now and i am able to create the file but the data from the qtablewidget is still not written in the excel file

def export(self):
        filename, filter = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '','Excel files (*.xlsx)')
        wb = Workbook()
        sheet = wb.active
        if not filename:
            for column in range(self.tableWidget.columnCount()):
                for row in range(self.tableWidget.rowCount()):
                    try:
                        text = str(self.tableWidget.item(row, column).text())
                        sheet.write(row, column, text)                    
                    except AttributeError:
                        pass
        wb.save(filename)

i tried printing the data from the qtablewidget and it shows, it just doesn't save in the excel file, is there still something missing?

So your line wb.save(filename) is inside your for loop, thereby the same filename is being saved on every loop.

Move that line outside and after the for loops at the outer indentation and therefore save it only once.

Also, ensure that the filename does not already exist, else you may get a pop dialog "Are you sure?" and you then need to force save it.

Almost all static methods of QFileDialog (except for getExistingDirectory() and getExistingDirectoryUrl() ) return a tuple in the form of (file(s), filter) .

For getOpenFileNames() (note the plural) the first object is a list of strings indicating the selected files, in the other cases it's the file path as a string or URL.

Do note that if the dialog is canceled, the file string (or the list) is empty, so you should check that before going on with the file writing:

    filename, filter = QtWidgets.QFileDialog.getSaveFileName(
        self, 'Save file', '','Excel files(*.xlsx)')
    if not filename:
        return
    # ...

Also, you should not try to save the file at each cycle of the for loop.

While 99% of the functions in Qt behave in the same way in PyQt, that's not always true, especially for situations for which C++ uses referenced variables. Whenever you are not sure about a function or get unexpeted behavior from it, you can check the PyQt documentation (the returned type(s) are specified at the end of the function definition, after the →) or just call help(class.function) in the python consolle. An even simpler solution is to just print the returned value, and you'll see that for yourself.

def imag_Export_Report(self):  
    self.cur.execute('''SELECT name, phone, image FROM photo''')
    rows = self.cur.fetchall()
    excel_file = QtWidgets.QFileDialog.getSaveFileName(self, "save file",'./','Excel Files (*.xlsx)')
    workbook = xlsxwriter.Workbook(excel_file[0])
    sheet1 = workbook.add_worksheet()
    sheet1.write(0, 0, 'name ') 
    sheet1.write(0, 1, ' phone')
    sheet1.write(0, 2, 'image ')

    row_number = 1  
    for row in rows:
        column_number = 0  
        for item in row:
            sheet1.write(row_number, column_number, str(item))
            column_number += 1
        row_number += 1
    workbook.close()
    self.con.commit()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM