在带有标题的excel中导出表格小部件

时间:2019-01-02 17:20:33

标签: python pyqt pyqt5 qtablewidget

我需要将表格小部件导出为包含垂直和水平标题的excel文件

此代码允许执行此操作,但没有标题:

    def createTable(self):
   # Create table
    self.tableWidget = QTableWidget()
    self.tableWidget.setRowCount(4)
    self.tableWidget.setColumnCount(2)
    self.tableWidget.setHorizontalHeaderLabels(['a','b'])
    print(self.tableWidget.horizontalHeaderItem(1).text())
    self.tableWidget.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
    self.tableWidget.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
    self.tableWidget.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
    self.tableWidget.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
    self.tableWidget.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
    self.tableWidget.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
    self.tableWidget.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
    self.tableWidget.setItem(3,1, QTableWidgetItem("Cell (4,2)"))
    self.tableWidget.move(0,0)

    # table selection change
    self.tableWidget.doubleClicked.connect(self.on_click_table)

def savefile(self):
    filename = QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)")
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
    for currentColumn in range(self.tableWidget.columnCount()):
        for currentRow in range(self.tableWidget.rowCount()):
            teext = str(self.tableWidget.item(currentRow, currentColumn).text())
            sheet.write(currentRow, currentColumn, teext)
    wbk.save(filename[0])

这是输出:

enter image description here

如何包含标头?

Tks

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用模型而不是项目,并且想法只是移动索引:

def savefile(self):
    filename,_ = QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)")
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.bold = True
    style.font = font
    model = self.tableWidget.model()
    for c in range(model.columnCount()):
        text = model.headerData(c, QtCore.Qt.Horizontal)
        sheet.write(0, c+1, text, style=style)

    for r in range(model.rowCount()):
        text = model.headerData(r, QtCore.Qt.Vertical)
        sheet.write(r+1, 0, text, style=style)

    for c in range(model.columnCount()):
        for r in range(model.rowCount()):
            text = model.data(model.index(r, c))
            sheet.write(r+1, c+1, text)
    wbk.save(filename)