将 QTableWidget 写入 .csv 或 .xls [英] writing a QTableWidget to a .csv or .xls

查看:111
本文介绍了将 QTableWidget 写入 .csv 或 .xls的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 QTableWidget 的内容写入 csv?我发现了一个关于使用 xlwt 写入 .xls 的问题,但似乎无法使用我的代码使其正常工作.

Is it possible to write the contents of a QTableWidget to a csv? I found a question about writing to an .xls using xlwt, but can't seem to get it to work using my code.

def saveFile(self):
    filename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)"))    
    wbk = xlwt.Workbook()
    self.sheet = wbk.add_sheet("sheet")
    self.write()
    wbk.save(filename)    


def write(self):
    for col in range (self.coordinates.columnCount()):
        for row in range(self.coordinates.rowCount()):
            text=str(self.coordinates.item(row,col).text())
            self.sheet.write(row,col,text)

我收到以下错误:

  File "C:\Users\Tory\Desktop\DIDSON.py", line 186, in saveFile
    self.write()
  File "C:\Users\Tory\Desktop\DIDSON.py", line 192, in write
    text=str(self.coordinates.item(row,col).text())
AttributeError: 'NoneType' object has no attribute 'text'

这是为什么?self.coordinates 是一个 QTableWidget.我能够将项目本身成功保存到工作表中,尽管我仍然想保存为 .csv ...

Why is this? self.coordinates is a QTableWidget. I was able to get the items themselves to save successfully to a worksheet, although I'd still like to save as a .csv...

推荐答案

回答关于AttributeError的问题:这可能是因为表中有一些空行或列.

To answer the question about the AttributeError: it probably happens because there are some empty rows or columns in the table.

一个空单元格没有分配给它QTableWidgetItem,所以table.item() 将返回None(显然没有'text' 属性).

An empty cell has no QTableWidgetItem assigned to it, so table.item() will return None (which obviously has no 'text' attribute).

要将表格另存为 csv,请尝试以下示例(它也可以打开 csv 文件,并有望处理任何潜在的 unicode 问题):

For saving the table as csv, try the example below (which can also open csv files, and hopefully deals with any potential unicode issues):

import sys, csv
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns - 1):
            for row in range(rows - 1):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        self.buttonOpen = QtGui.QPushButton('Open', self)
        self.buttonSave = QtGui.QPushButton('Save', self)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.buttonOpen)
        layout.addWidget(self.buttonSave)

    def handleSave(self):
        path = QtGui.QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'wb') as stream:
                writer = csv.writer(stream)
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                unicode(item.text()).encode('utf8'))
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)

    def handleOpen(self):
        path = QtGui.QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'rb') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QtGui.QTableWidgetItem(data.decode('utf8'))
                        self.table.setItem(row, column, item)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window(10, 5)
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

这篇关于将 QTableWidget 写入 .csv 或 .xls的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆