简体   繁体   English

如何在不删除其列和数据的情况下将 excel 文件添加到 QTableWidget?

[英]How to add excel file to QTableWidget without erasing its column and data?

How do i load excel data to QTableWidget?如何将 excel 数据加载到 QTableWidget? I want it to appear after the last recipient data我希望它出现在最后一个收件人数据之后

这是我的列和数据

这是我导入我的excel文件的时候。

This is the code i used:这是我使用的代码:

 def addExcel(self, excel_file_dir, worksheet_name):
    df = pd.read_excel(excel_file_dir, worksheet_name)
    if df.size == 0:
            return 

    df.fillna('', inplace=True)
    self.tableWidget.setRowCount(df.shape[0])
    self.tableWidget.setColumnCount(df.shape[1])

    for row in df.iterrows():
            values = row[1]
            for col_index, value in enumerate(values):
                    if isinstance(value, (float, int)):
                            value = '{0:0,.0f}'.format(value)
                    tableItem = QTableWidgetItem(str(value))
                    self.tableWidget.setItem(row[0], col_index, tableItem)

As the documentation of setRowCount() explains:正如setRowCount()的文档所解释的:

Sets the number of rows in this table's model to rows.将此表的模型中的行数设置为行。 If this is less than rowCount(), the data in the unwanted rows is discarded.如果这小于 rowCount(),则丢弃不需要的行中的数据。

The same clearly goes for setColumnCount() as well. setColumnCount()显然也是如此。

If you want to preserve existing data, you obviously have to add the row and column count based on the new data.如果要保留现有数据,显然必须根据新数据添加行数和列数。

Considering that data models usually increase the number of records ( rows ) while keeping the columns, you have to call setRowCount() by increasing the current row count by the number of new records, and set the column count based on the maximum between the existing column count and the retrieved one.考虑到数据模型通常会在保留列的同时增加记录数(),因此您必须通过将当前行数增加新记录数来调用setRowCount() ,并根据现有记录之间的最大值设置列数列数和检索到的列数。

def addExcel(self, excel_file_dir, worksheet_name):
    df = pd.read_excel(excel_file_dir, worksheet_name)
    if df.size == 0:
            return 

    df.fillna('', inplace=True)

    newFirstRow = self.tableWidget.rowCount()
    self.tableWidget.setRowCount(newFirstRow + df.shape[0])
    self.tableWidget.setColumnCount(
        max(self.tableWidget.columnCount(), df.shape[1]))

    for rowData in df.iterrows():
        row = newFirstRow + rowData[0]
        values = rowData[1]
        for col_index, value in enumerate(values):
            if isinstance(value, (float, int)):
                value = '{0:0,.0f}'.format(value)
                tableItem = QTableWidgetItem(str(value))
                self.tableWidget.setItem(row, col_index, tableItem)

Note: '{0:0,.0f}'.format(value) is quite pointless in most cases: you can just use str(round(value)) instead.注意: '{0:0,.0f}'.format(value)在大多数情况下是毫无意义的:你可以使用str(round(value))代替。

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

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