簡體   English   中英

使用 Python 將文本文件插入現有的 xlsx

[英]insert text file into existing xlsx using Python

我有一個包含 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'

有什么建議嗎?

似乎(而且我絕不了解那些特定的庫)您試圖在這些行中將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)

考慮這個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM