python读写excel的简单方法demo

import xlrd
import xlwt

class ExcelHelper:
    #读取excel,返回数组
    @classmethod
    def readExcel(self,filename):
        workbook = xlrd.open_workbook(filename)
        sheet = workbook.sheets()[0]
        rowcount = sheet.nrows
        data = [sheet.row_values(i) for i in range(rowcount)]
        for i in range(1,len(data)):
            data[i][0] = DateHelper.getdate(data[i][0])
        return data

    #写入excel
    @classmethod
    def writeXls(self,filePath,data):
        filename = xlwt.Workbook(encoding='utf-8')
        sheet = filename.add_sheet('sheet1',cell_overwrite_ok=True)
        rowcnt = len(data[1])
        colcnt = len(data[0])
        map(lambda cols:sheet.write(0,cols,data[0][cols]),range(colcnt))
        for rowid in range(rowcnt):
            for cols in range(colcnt):
                if data[1][rowid][cols] is None:
                    sheet.write(rowid+1,cols,'')
                else:
                    sheet.write(rowid+1,cols,str(data[1][rowid][cols]))
            # map(lambda cols : sheet.write(rowid+1,cols,str(data[1][rowid][cols])),range(colcnt))
        filename.save(filePath)

 

posted @ 2013-10-30 09:48  一个坟头  阅读(1718)  评论(0编辑  收藏  举报