【问题标题】:Unable to close worksheet in xlsxwriter无法关闭 xlsxwriter 中的工作表
【发布时间】:2019-12-10 03:20:29
【问题描述】:

我正在尝试使用 xlsxwriter 创建一个 excel 工作簿,但是当我尝试执行 workbook.close() 时出现以下异常:

Traceback (most recent call last):
  File "/usr/local/bin/fab", line 11, in <module>
    sys.exit(program.run())
  File "/usr/local/lib/python2.7/site-packages/invoke/program.py", line 363, in run
    self.execute()
  File "/usr/local/lib/python2.7/site-packages/invoke/program.py", line 532, in execute
    executor.execute(*self.tasks)
  File "/usr/local/lib/python2.7/site-packages/invoke/executor.py", line 129, in execute
    result = call.task(*args, **call.kwargs)
  File "/usr/local/lib/python2.7/site-packages/invoke/tasks.py", line 128, in __call__
    result = self.body(*args, **kwargs)
  File "/app/fabfile.py", line 168, in test2
    workbook.close()
  File "/usr/local/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 304, in close
    self._store_workbook()
  File "/usr/local/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 676, in _store_workbook
    xlsx_file.write(os_filename, xml_filename)
  File "/usr/lib64/python2.7/zipfile.py", line 1146, in write
    zinfo.header_offset = self.fp.tell()    # Start of header bytes
AttributeError: 'tuple' object has no attribute 'tell'
Exception AttributeError: "'tuple' object has no attribute 'tell'" in <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0x7f87fcffa410>> ignored

我正在查询一个数据库,然后创建 3 张工作表并在其中填写表格,代码如下:

def summary_main():
        start_time = time.time()

        print "starting job}"
        ##setup db and extract summaries
        files_last_date = input("date in yyyy-mm-dd")
        sql_h = SqlHelper()
        date = datetime.today().strftime("%Y-%m-%d")
        file_name=('/app/SUMMARY_',date,'.xlsx')
        print "file name created = ",file_name
        workbook = xlsxwriter.Workbook(file_name)
        get_uploaded_files(workbook,files_last_date,sql_h)

        # getting exception in the following line
        workbook.close()
        print "\n\nSummary has been saved, workbook closed"

上面的代码在我的本地机器上的 python3 中运行良好,但是在服务器上我们试图在 python2 上运行相同的代码,这是代码不起作用的原因吗?在最后一行抛出异常,这意味着在此之前没有兼容性问题。在 get_uploaded_files 函数中,我查询数据库并将数据写入工作表,如下所示:

def get_uploaded_files(wb,dt,sql_h):
    sheet = wb.add_worksheet("Uploaded Files")
    data_set = sql_h.getData(dt,1)
    header = ["File ID", "First Name", "Last Name", "File Name", "Comments"]
    sql_h.parse_sql_data(sheet,header,data_set,wb)

以下 2 个函数在名为 SqlHelper_py2.py 的单独文件中定义

def getData(self,dt,case):
        print(self.conn)
        cur=self.conn.cursor()
        data_set=""
        if case==1:
            cur.execute(self.sql_uploaded_file.replace("%s",str(dt)))
            data_set=cur.fetchall()
        cur.close()
        return data_set


def parse_sql_data(self,sheet,header,data_set,workbook):
        format_bold=workbook.add_format({'bold': True,'border':1})
        format_border=workbook.add_format({'border':1})
        col = 0
        count=0
        dict_max={0:0}
        for h in header:
            sheet.write(0,col,h,format_bold)
            col+=1
            dict_max[count]=len(str(h))
            count+=1
        row = 1
        for data in data_set:
            col=0
            for d in data:
                if(dict_max[col] is not None and len(str(d))>dict_max[col]):
                    dict_max[col]=len(str(d))
                if("datetime.datetime" not in str(type(d))): 
                    sheet.write(row,col,d,format_border)
                col+=1
            row+=1
        for key in dict_max: 
            sheet.set_column(key,key,dict_max[key]+5)

【问题讨论】:

  • 确保xlsxwriter 版本相同。如果两者都需要支持 Python 2 和 3,这可能是一个挑战
  • @DeepSpace 我创建了以下演示代码来测试它是否有效:def test3():workbook = xlsxwriter.Workbook('/app/cdpgrp/gp_brms/hello.xlsx')worksheet = workbook.add_worksheet()worksheet.write('A1', 'Hello..') worksheet.write('A1', 'Hello..') worksheet.write('B1', 'Geeks') workbook.close() 并且此代码工作正常,能够创建excel表格,所以我不认为xlsxwriter的版本有问题。
  • 请注意,异常发生在 zipfile 而不是 xlsxwriter 中。是因为某些权限问题吗?简单的 hello_world.py 案例在两个平台上都可以正常工作吗?
  • @jmcnamara 两个代码都在同一个环境中运行,如果有一些权限错误,那么 helloworld 也不会工作,对吧?我是python新手,所以我主要是在猜测,我来自java背景
  • @gpd 如果 hello world 示例在两种环境中都有效,那么这不是权限问题。我认为您需要通过删除功能来调试它,直到您有一个工作示例(最小目标中的 hello world)。我是 XlsxWriter 的作者/维护者,我从未见过这样的问题,也没有任何 Python 2/3 兼容性问题。

标签: python python-2.7 mysql-python xlsxwriter


【解决方案1】:

以上代码在我本地机器上的 python3 中运行良好

我觉得这很难相信,因为您使用了 print 语句,这会导致 Python 3 出现语法错误。无论如何,回到您的主要问题:

AttributeError: 'tuple' 对象没有属性 'tell'

tell 是文件对象的方法。不知何故,xlswriter 在它需要一个文件对象的地方持有一个元组。我们是否在您的代码中看到任何可疑的元组?是的:

    file_name=('/app/SUMMARY_',date,'.xlsx')
    workbook = xlsxwriter.Workbook(file_name)

您的file_name 不是字符串,而是字符串元组。 xlsxwriter.Workbook 需要一个字符串或一个文件对象。当它看到你没有给它传递一个字符串时,它认为它必须是一个文件对象。

要解决这个问题,请将文件名的各个部分连接成一个实际的字符串:

    file_name = ''.join('/app/SUMMARY_',date,'.xlsx')

【讨论】:

    猜你喜欢
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2013-08-02
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多