难以从QTableWidget导出CSV数据

10 浏览
0 Comments

难以从QTableWidget导出CSV数据

这个问题已经在这里有答案了:

TypeError: a bytes-like object is required, not \'str\' in python and CSV

所以我正在尝试编写代码,将CSV文件加载到每个选项卡中的QTableWidget中,然后可以编辑并保存在其上方。但是,当我保存时,程序因各种原因而崩溃。虽然自动加载尚未设置,但我正在试图一次解决一个问题!

我看到了很多看起来询问同样的问题的帖子,但是在实施它们时,它们似乎不起作用,一些是因为它们使用tableview而不是QTableWidget,一些可能是因为我在编码方面失败。因为我是新手。

class MyTabs(QWidget):

def __init__(self, parent):
    super(QWidget, self).__init__(parent)
    layout = QVBoxLayout(self)
    # Initialize tab screen
    self.tabs = QTabWidget()
    self.tabmon = QWidget()
    self.tabtue = QWidget()
    # Add tabs
    self.tabs.addTab(self.tabmon, "Monday")
    self.tabs.addTab(self.tabtue, "Tuesday")
    #Save Button
    self.buttonSavemon = QtWidgets.QPushButton('Save', self)
    self.buttonSavemon.clicked.connect(self.handleSavemon)
    self.buttonSavetue = QtWidgets.QPushButton('Save', self)
    self.buttonSavetue.clicked.connect(self.handleSavetue)
    #Initiate Tables
    self.createTable()
    # Create Monday tab
    self.tabmon_layout = QVBoxLayout(self.tabmon)
    self.tabmon_layout.addWidget(self.tablewidgetmon)
    self.tabmon_layout.addWidget(self.buttonSavemon)
    # Create Tuesday tab
    self.tabtue_layout = QVBoxLayout(self.tabtue)
    self.tabtue_layout.addWidget(self.tablewidgettue)
    self.tabtue_layout.addWidget(self.buttonSavetue)
    # Add tabs to widget
    layout.addWidget(self.tabs)
def createTable(self):
    #Monday Table
    self.tablewidgetmon = QTableWidget()
    self.tablewidgetmon.setRowCount(10)
    self.tablewidgetmon.setColumnCount(2)
    self.tablewidgetmon.setHorizontalHeaderLabels(["Time", "File Name"])
    #Tuesday Table
    self.tablewidgettue = QTableWidget()
    self.tablewidgettue.setRowCount(12)
    self.tablewidgettue.setColumnCount(2)
    self.tablewidgettue.setHorizontalHeaderLabels(["Time", "File Name"])
def handleSavemon(self):
    with open('monschedule.csv', 'wb') as stream:
        writer = csv.writer(stream)
        for row in range(self.tablewidgetmon.rowCount()):
            rowdata = []
            for column in range(self.tablewidgetmon.columnCount()):
                item = self.tablewidgetmon.item(row, column)
                if item is not None:
                    rowdata.append(
                        unicode(item.text()).encode('utf8'))
                else:
                    rowdata.append('')
            writer.writerow(rowdata)
def handleSavetue(self):
    with open('tueschedule.csv', "w") as fileOutput:
        writer = csv.writer(fileOutput)
        for rowNumber in range(self.tablewidgettue.rowCount()):
            fields = [
                self.tablewidgettue.data(
                    self.tablewidgettue.index(rowNumber, columnNumber),
                    QtCore.Qt.DisplayRole
                )
                for columnNumber in range(self.tablewidgettue.columnCount())
            ]
            writer.writerow(fields)

我在这里尝试了两种方法来保存,星期一函数似乎是最有前途的,但是因为数据是字符串而给我带来了错误。

从之后查看CSV文件,似乎它已经清除了原始文件,但没有保存新数据。

admin 更改状态以发布 2023年5月20日
0
0 Comments

尝试一下:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
import csv
class MyTabs(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        layout = QVBoxLayout(self)
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tabmon = QWidget()
        self.tabtue = QWidget()
        # Add tabs
        self.tabs.addTab(self.tabmon, "Monday")
        self.tabs.addTab(self.tabtue, "Tuesday")
        #Save Button
        self.buttonSavemon = QtWidgets.QPushButton('Save', self)
        self.buttonSavemon.clicked.connect(self.handleSavemon)
        self.buttonSavetue = QtWidgets.QPushButton('Save', self)
        self.buttonSavetue.clicked.connect(self.handleSavetue)
        #Initiate Tables
        self.createTable()
        # Create Monday tab
        self.tabmon_layout = QVBoxLayout(self.tabmon)
        self.tabmon_layout.addWidget(self.tablewidgetmon)
        self.tabmon_layout.addWidget(self.buttonSavemon)
        # Create Tuesday tab
        self.tabtue_layout = QVBoxLayout(self.tabtue)
        self.tabtue_layout.addWidget(self.tablewidgettue)
        self.tabtue_layout.addWidget(self.buttonSavetue)
        # Add tabs to widget
        layout.addWidget(self.tabs)
    def createTable(self):
        #Monday Table
        self.tablewidgetmon = QTableWidget()
        self.tablewidgetmon.setRowCount(10)
        self.tablewidgetmon.setColumnCount(2)
        self.tablewidgetmon.setHorizontalHeaderLabels(["Time", "File Name"])
        #Tuesday Table
        self.tablewidgettue = QTableWidget()
        self.tablewidgettue.setRowCount(12)
        self.tablewidgettue.setColumnCount(2)
        self.tablewidgettue.setHorizontalHeaderLabels(["Time", "File Name"])
    def handleSavemon(self):
#        with open('monschedule.csv', 'wb') as stream:
        with open('monschedule.csv', 'w') as stream:                  # 'w'
            writer = csv.writer(stream, lineterminator='\n')          # + , lineterminator='\n'
            for row in range(self.tablewidgetmon.rowCount()):
                rowdata = []
                for column in range(self.tablewidgetmon.columnCount()):
                    item = self.tablewidgetmon.item(row, column)
                    if item is not None:
#                        rowdata.append(unicode(item.text()).encode('utf8'))
                        rowdata.append(item.text())                   # +
                    else:
                        rowdata.append('')
                writer.writerow(rowdata)
    def handleSavetue(self):
        with open('tueschedule.csv', "w") as fileOutput:
            writer = csv.writer(fileOutput)
            for rowNumber in range(self.tablewidgettue.rowCount()):
# +                
                fields = [
                    self.tablewidgettue.item(rowNumber, columnNumber).text() \
                            if self.tablewidgettue.item(rowNumber, columnNumber) is not None else ""
                    for columnNumber in range(self.tablewidgetmon.columnCount())
                ]                
                writer.writerow(fields)
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    main = MyTabs()
    main.show()
    sys.exit(app.exec_()) 

enter image description here

0
0 Comments

你正在将文件作为二进制文件打开,而不是文本文件。这就是为什么writerow函数期望一个类似字节的对象的原因。

要解决这个问题,就需要在open函数中移除'b'标志:

with open('monschedule.csv', 'w') as stream:

顺便说一下,行rowdata.append(unicode(item.text()).encode('utf8'))应该是rowdata.append(item.text())

0