python 追加写入到excel

# -*- coding: utf-8 -*-
from xlwt import *
import os
import oss2
from xlrd import open_workbook
from xlutils.copy import copy
import datetime
import random
import sys
import traceback


PREFIX = 'http://'

class cexport_excel():

    """excel追加写入"""
    # excheader表头
    # datasrcset  二维元祖
    # path = 'hh.xls'
    def export_excel(self,path,excname,excheader,datasrcset,username, ossinfo,urlload):
        result = {}
        try:
            # 写头
            if not os.path.exists(path):
                w = Workbook()
                sheet = w.add_sheet(excname)
                headercol = 0
                for header in excheader:
                    sheet.write(0, headercol, str(header).decode('utf-8'))
                    headercol += 1
                w.save(path)

            # 追加写入excel
            rexcel = open_workbook(path)
            rows = rexcel.sheets()[0].nrows
            excel = copy(rexcel)
            table = excel.get_sheet(0)
            newrow = rows
            for i, row in enumerate(datasrcset):
                for j, col in enumerate(row):
                    table.write(newrow, j, col)  # datasrcset
                newrow += 1
            excel.save(path)

            osspath = username + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '_' + str(random.randint(0, 99)) + '.xls'
            auth = oss2.Auth(ossinfo['ACCESS_KEY_ID'], ossinfo['ACCESS_KEY_SECRET'])
            bucket = oss2.Bucket(auth, ossinfo['ENDPOINT_OUT'], ossinfo['BUCKETNAME_XLS'])
            bucket.put_object('%s/%s' % (urlload, osspath), open(path))
            result['osspath'] = PREFIX + ossinfo['BUCKETNAME_XLS'] + '.' + ossinfo['ENDPOINT_OUT'] + '/' + urlload + '/' + osspath
            result['errorcode'] = 0
            return result
        except Exception as ex:
            result['errorcode'] = -1
            result['errortext'] = '%s:Exception = %s ex=%s  __LINE__=%s' % (traceback.print_exc(), Exception, ex, sys._getframe().f_lineno)
            return result
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值