'Convert entire table (or just selected area) into tab-separated text values'

def serialize(self, useSelection=False):

    if useSelection:
        selection = self.selectedRanges()[0]
        rows = list(range(selection.topRow(), (selection.bottomRow() + 1)))
        columns = list(range(selection.leftColumn(), (selection.rightColumn() + 1)))
    else:
        rows = list(range(self.rowCount()))
        columns = list(range(self.columnCount()))
    data = []
    if self.horizontalHeadersSet:
        row = []
        if self.verticalHeadersSet:
            row.append(asUnicode(''))
        for c in columns:
            row.append(asUnicode(self.horizontalHeaderItem(c).text()))
        data.append(row)
    for r in rows:
        row = []
        if self.verticalHeadersSet:
            row.append(asUnicode(self.verticalHeaderItem(r).text()))
        for c in columns:
            item = self.item(r, c)
            if (item is not None):
                row.append(asUnicode(item.value))
            else:
                row.append(asUnicode(''))
        data.append(row)
    s = ''
    for row in data:
        s += (' DCTB '.join(row) + '\n')
    return s
