gpt4 book ai didi

python - PyQt 从 excel 填充 QTableWidget

转载 作者:行者123 更新时间:2023-12-01 02:44:56 35 4
gpt4 key购买 nike

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

输出:

enter image description here

关于python - PyQt 从 excel 填充 QTableWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45349252/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com