当前位置: 主页 > 日志 > Python >

XLSWriter

xlwt进行了一个简单的包装,便于按行输出。

以后给国内客户尽量提供xls格式的输出(utf-8格式的csv不方便Excel用户使用)。

鉴于32位系统下Excel的65535行数的限制,XLSWriter进行了自动分表。

# coding: utf-8
# xlswriter.py

# http://pypi.python.org/pypi/xlwt
import xlwt

class XLSWriter(object):
    """A XLS writer that produces XLS files from unicode data.
    """
    def __init__(self, file, encoding='utf-8'):
        # must specify the encoding of the input data, utf-8 default.
        self.file = file
        self.encoding = encoding
        self.wbk = xlwt.Workbook()
        self.sheet_index = 0
        self.header = []
        self.create_sheet()
        
    def create_sheet(self):
        self.sheet_index += 1
        self.sheet = self.wbk.add_sheet('sheet %d' % self.sheet_index, cell_overwrite_ok=True)
        self.rows_num = 0

    def cell(self, s):
        if isinstance(s, basestring):
            if not isinstance(s, unicode):
                s = s.decode(self.encoding)
        elif s is None:
            s = ''
        else:
            s = str(s)
        return s

    def writerow(self, row):
        if self.rows_num == 0:
            self.header = row
        if self.rows_num >= 65534:
            self.save()
            self.create_sheet()
            if self.header:
                self.writerow(self.header)
        for ci, col in enumerate(row):
            self.sheet.write(self.rows_num, ci , self.cell(col))
        self.rows_num += 1
            
    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

    def save(self):
        self.wbk.save(self.file)
        
if __name__ == '__main__':
    import csv
    # test
    # convert a existing CSV file to XLS file
    xlswriter = XLSWriter('hc360.xls')
    for row in csv.reader(open('hc360.csv')):
        xlswriter.writerow(row)
    # don't forget to save data to disk
    xlswriter.save()
    print 'finished.'

[日志信息]

该日志于 2012-09-03 16:35 由 redice 发表在 redice's Blog ,你除了可以发表评论外,还可以转载 “XLSWriter” 日志到你的网站或博客,但是请保留源地址及作者信息,谢谢!!    (尊重他人劳动,你我共同努力)
   
验证(必填):   点击我更换验证码

redice's Blog  is powered by DedeCms |  Theme by Monkeii.Lee |  网站地图 |  本服务器由西安鲲之鹏网络信息技术有限公司友情提供

返回顶部