python tips

excel2text

#!/usr/bin/env python
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import xlrd
from datetime import time
from datetime import datetime
from xlrd import xldate_as_tuple

args = sys.argv

input_file = args[1]
output_file = args[2]

data = xlrd.open_workbook(input_file)
print(type(data))
table = data.sheets()[0]
nrows = table.nrows
ncols = table.ncols

f = open(output_file, 'w')
for iRow in range(1,nrows):
    row = []
    for iCol in range(ncols):
        sCell = table.cell_value(iRow,iCol)
        ctype = table.cell(iRow,iCol).ctype
        if ctype == 3:
            try:
                year, month, day, hour, minute, second = xldate_as_tuple(sCell, 0)
                if sCell < 1:
                    sCell = str(time(hour, minute, second))
                else:
                    sCell = str(datetime(year, month, day, hour, minute, second))
            except:
                sCell = str(sCell)
        elif ctype == 2 and sCell % 1 == 0:
            sCell = str(int(sCell))
        elif ctype == 4:
            sCell = True if sCell == 1 else False
        else:
            sCell = str(sCell)
        row.append(sCell)
    f.write('\t'.join(row) + '\n')
f.close()
posted @ 2022-01-19 14:33  畑鹿驚  阅读(29)  评论(0编辑  收藏  举报