如何在不删除其列和数据的情况下将Excel文件添加到QTableWidget?
如何将Excel数据加载到QTableWidget? 之后出现。
“ https://i.sstatic.net/bpjad.png” alt =“这是我导入我的excel文件的时候。”>
这是我使用的代码:
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)
How do i load excel data to QTableWidget? I want it to appear after the last recipient data
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为
对于
setColumnCount()
,也显然也是如此。如果要保留现有数据,则显然必须根据新数据添加 。
考虑到数据模型通常会在保留列时增加记录的数量( lows ),您必须通过增加当前来调用
setRowCount()
行计算新记录的数量,并根据现有列计数和检索到的列之间的最大值设置列计数。注意:
'{0:0,.0f}'。格式(value)
在大多数情况下是毫无意义的:您只需使用str(round> str(round(value))。
As the documentation of
setRowCount()
explains:The same clearly goes for
setColumnCount()
as well.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.Note:
'{0:0,.0f}'.format(value)
is quite pointless in most cases: you can just usestr(round(value))
instead.