如何使用从xlrd读取的格式并在python中写入xlsxwriter

时间:2016-08-14 23:57:09

标签: python-2.7 xlrd xlsxwriter

我正在使用xlrd读取excel文件。做一些宏替换,然后通过xlsxwriter写。没有读取和复制格式信息代码工作,但当我添加格式信息时,我得到一个错误(在底部) 代码片段在下面..我读了一个xls文件,对于每个数据行,我用值替换令牌宏并写回。当我尝试关闭output_workbook时出现错误

    filePath = os.path.realpath(os.path.join(inputPath,filename))
    input_workbook = open_workbook(filePath, formatting_info=True)
    input_DataSheet = input_workbook.sheet_by_index(0)
    data = [[input_DataSheet.cell_value(r,c) for c in range(input_DataSheet.ncols)] for r in range(input_DataSheet.nrows)]

    output_workbook = xlsxwriter.Workbook('C:\Users\Manish\Downloads\Sunny\Drexel_Funding\MacroReplacer\demo.xlsx')
    output_worksheet = output_workbook.add_worksheet()

    for rowIndex, value in enumerate(data):
        copyItem = []

        for individualItem in value:
            tempItem = individualItem

            if (isinstance(individualItem, basestring)):
                tempItem = tempItem.replace("[{0}]".format(investorNameMacro), investorName)
                tempItem = tempItem.replace("[{0}]".format(investorPhoneMacro), investorPhone)
                tempItem = tempItem.replace("[{0}]".format(investorEmailMacro), investorEmail)
                tempItem = tempItem.replace("[{0}]".format(loanNumberMacro), loanNumber)

            copyItem.append(tempItem)

        for columnIndex, val in enumerate(copyItem):
            fmt =input_workbook.xf_list[input_DataSheet.cell(rowIndex,columnIndex).xf_index]
            output_worksheet.write(rowIndex,columnIndex, val,fmt)

    output_workbook.close()

我得到的错误是

追踪(最近一次通话):   文件“C:/Users/Manish/Downloads/Sunny/Drexel_Funding/MacroReplacer/drexelfundingmacroreplacer.py”,第87行,     output_workbook.close()   文件“build \ bdist.win-amd64 \ egg \ xlsxwriter \ workbook.py”,第297行,关闭   在_store_workbook中输入“build \ bdist.win-amd64 \ egg \ xlsxwriter \ workbook.py”,第605行   在_create_package文件“build \ bdist.win-amd64 \ egg \ xlsxwriter \ packager.py”,第131行   文件“build \ bdist.win-amd64 \ egg \ xlsxwriter \ packager.py”,第189行,在_write_worksheet_files中   在_assemble_xml_file中输入“build \ bdist.win-amd64 \ egg \ xlsxwriter \ worksheet.py”,第3426行   在_write_sheet_data中输入“build \ bdist.win-amd64 \ egg \ xlsxwriter \ worksheet.py”,第4829行   在_write_rows中输入“build \ bdist.win-amd64 \ egg \ xlsxwriter \ worksheet.py”,第5015行   _write_cell中的文件“build \ bdist.win-amd64 \ egg \ xlsxwriter \ worksheet.py”,第5183行 AttributeError:'XF'对象没有属性'_get_xf_index'

感谢任何帮助

由于

1 个答案:

答案 0 :(得分:1)

Xlrd和XlsxWriter格式是不同的对象类型,不可互换。

如果您希望保留格式,则必须编写一些代码,将属性从一个转换为另一个。