PyQt从excel填充QTableWidget

时间:2017-07-27 11:15:53

标签: python excel pyqt openpyxl qtablewidget

我试图用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)

1 个答案:

答案 0 :(得分:2)

要向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)

输出:

enter image description here