PyQt 从 excel 填充 QTableWidget

PyQt populate QTableWidget from excel

我试图用 excel 文件中的一些数据填充 QTableWidget,我只想在 ID 位于 listID 上时向我的 QTable 添加行,并且我在 QTable 单元格中没有数据

https://drive.google.com/file/d/0B_PFK3V2Ij4tSko4emplYmNuN1E/view?usp=sharing 这里是一个 excel 文件,它不包含任何格式或公式,只有空行和列,因为文件是自动生成的

这是我的代码

wb = openpyxl.load_workbook(os.path.join(os.getcwd(), file), read_only=True)
ws = wb.active

headers = []
for item in ws[4]:
    headers.append(item.value)
headers.pop(0)

listID = []
for index in range(self.listWidgetID.count()):
    listID.append(self.listWidgetID.item(index).text())

data = ws.iter_rows(row_offset=5, column_offset=1)

row_increment = 0
self.tableWidgetDATA.setRowCount(1)
self.tableWidgetDATA.setColumnCount(len(headers))
self.tableWidgetDATA.setHorizontalHeaderLabels(headers)

for x, rows in enumerate(data):
    if str(rows[0].value) in listID:
        for y, cell in enumerate(rows):
            item = QTableWidgetItem(str(cell.value))
            self.tableWidgetDATA.setItem(x, y, item)
        row_increment = row_increment + 1
        self.tableWidgetDATA.setRowCount(row_increment)

要向QTableWidget添加元素,位置必须是setRowCount(),你的情况是添加后更新,所以不会保存,另一个错误是你没有验证是否数据有效。

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.tableWidgetDATA = QTableWidget(self)
        self.listWidgetID = QListWidget(self)
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(self.listWidgetID)
        self.layout().addWidget(self.tableWidgetDATA)
        self.listWidgetID.addItems(["113894", "113906", "113895"])
        file = "Livro2.xlsx"
        wb = openpyxl.load_workbook(os.path.join(os.getcwd(), file), read_only=True)
        ws = wb.active

        headers = [item.value for item in ws[4] if item.value is not None]

        listID = [self.listWidgetID.item(i).text() for i in range(self.listWidgetID.count())]

        data = ws.iter_rows(row_offset=5, column_offset=1)

        self.tableWidgetDATA.setColumnCount(len(headers))
        self.tableWidgetDATA.setHorizontalHeaderLabels(headers)

        for x, rows in enumerate(data):
            if rows[0].value is not None:
                if str(rows[0].value) in listID:
                    self.tableWidgetDATA.setRowCount(self.tableWidgetDATA.rowCount()+1)
                    for y, cell in enumerate(rows):
                        val = cell.value
                        if val is not None:
                            item = QTableWidgetItem(str(val))
                            self.tableWidgetDATA.setItem(self.tableWidgetDATA.rowCount()-1, y, item)

输出: