简体   繁体   English

如何使用openpyxl将qtablewidget数据保存到excel文件中

[英]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?我有一个包含数据的 qtablewidet,当用户单击导出按钮时,将出现一个对话框,要求将文件名另存为 excel,我如何使用 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当我尝试从对话框中单击保存时,现在的 output 就是这个

在此处输入图像描述

how do i save the whole data including the headers from qtablewidget to an excel file using openpyxl?我如何使用 openpyxl 将包括标题的整个数据从 qtablewidget 保存到 excel 文件?

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更新:我现在编辑了我的代码并且我能够创建文件但是来自 qtablewidget 的数据仍然没有写入 excel 文件

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?我尝试从 qtablewidget 打印数据,它显示,它只是没有保存在 excel 文件中,是否还缺少一些东西?

So your line wb.save(filename) is inside your for loop, thereby the same filename is being saved on every loop.因此,您的行 wb.save(filename) 在您的 for 循环中,因此每个循环都保存了相同的文件名。

Move that line outside and after the for loops at the outer indentation and therefore save it only once.将该行移到外部缩进的 for 循环之后,因此只保存一次。

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) . QFileDialog 的几乎所有 static 方法( getExistingDirectory()getExistingDirectoryUrl()除外)都以(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.对于getOpenFileNames() (注意复数),第一个 object 是指示所选文件的字符串列表,在其他情况下,它是字符串形式的文件路径或 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.此外,您不应尝试在 for 循环的每个循环中保存文件。

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.虽然 Qt 中 99% 的函数在 PyQt 中的行为方式相同,但这并不总是正确的,尤其是对于 C++ 使用引用变量的情况。 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.每当您不确定 function 或从中获得意外行为时,您可以查看PyQt 文档(返回的类型在 ZC1C425268E68385D1AB5074C17 的末尾指定或只调用help(class.function)之后的定义)。 help(class.function)在 python 控制台中。 An even simpler solution is to just print the returned value, and you'll see that for yourself.一个更简单的解决方案是只print返回的值,您会自己看到。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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