使用Python

时间:2017-06-01 08:33:56

标签: python excel xlsx openpyxl

我有一个包含11个工作表的.xlsx文件,我需要从第3行开始插入文本文件的内容(制表符分隔符,大约30列100行)。我尝试了下面的代码,但我最终得到了错误。 (使用bash / Linux)

#!/usr/bin/env python

import csv
from openpyxl.reader.excel import load_workbook
from xlrd import open_workbook
from xlutils import copy as xl_copy


with open('S12_final.txt') as tab_file: #open tab text file
    tab_reader = csv.reader(tab_file, delimiter='\t')
    xls_readable_book = load_workbook('S12.xlsx') #load workbook
    xls_writeable_book = xl_copy.copy(xls_readable_book)
    xls_writeable_sheet = xls_writeable_book.get_sheet_by_name('Filtered') #write data on this sheet
    for row_index, row in enumerate(tab_reader):
        xls_writeable_sheet.write(row_index, 0, row[0])
        xls_writeable_sheet.write(row_index, 1, row[1])
    xls_writeable_book.save('S12.xlsx') #save excel file

错误:

> Traceback (most recent call last):   File "./tab2excel_a.py", line 23,
> in <module>
>     xls_writeable_book = xl_copy.copy(xls_readable_book)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/copy.py",
> line 19, in copy
>     w   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 937, in process
>     reader(chain[0])   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 61, in __call__
>     filter.workbook(workbook,filename)   File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 287, in workbook
>     self.wtbook.dates_1904 = rdbook.datemode AttributeError: 'Workbook' object has no attribute 'datemode'

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您试图在这些行中将openpyxl对象输入xlutils方法似乎(并且我并不了解这些特定的库):

xls_readable_book = load_workbook('S12.xlsx') #load workbook
xls_writeable_book = xl_copy.copy(xls_readable_book)

所以解释器抱怨这个“未知”对象没有属性datemode。因此,请尝试使用xlrd open_workbook方法,因为它似乎返回了一个Book对象,根据文档,该对象与xlrd.copy方法完全兼容:

xls_readable_book = open_workbook('S12.xlsx') #load workbook
xls_writeable_book = xl_copy.copy(xls_readable_book)

答案 1 :(得分:0)

考虑这个openpyxl示例:

from openpyxl.workbook.workbook import Workbook # as _Workbook
import csv

wb = Workbook()
wb.create_sheet('Filtered')
ws = wb['Filtered']

with open('test/S12_final.csv') as tab_file:
    tab_reader = csv.reader(tab_file, delimiter='\t')

    # Skipt first 2 Lines
    [next(tab_reader) for skip in range(2)]

    # Append list(rowData) after Sheets last accessed Row
    for rowData in tab_reader:
        ws.append(rowData)

wb.save('test/S12.xlsx')

使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2