如何正确地将表添加到只写openpyxl工作表?

问题描述 投票:0回答:1

我正在尝试加载包含数据的 Excel 工作表,在其上放置一个表格,然后再次保存。不幸的是,我需要一种迂回的方法来做到这一点,因为 Excel 文件太大,无法使用 openpyxl 正常打开和保存(~120,000 行;保存时出现 MemoryError),所以我需要将其作为只读工作簿打开,然后将其写入新的只写工作簿。这就是我到目前为止所拥有的(标题是一个字符串数组,其长度与文件中的列数匹配):

import openpyxl
from openpyxl.worksheet.table import Table, TableStyleInfo
from openpyxl.utils import get_column_letter

# Load excel file
wb = openpyxl.load_workbook(excelFile, read_only=True)
ws = wb[wb.sheetnames[0]]

# Create table
maxRow = ws.max_row
maxCol = get_column_letter(ws.max_column)
tab = Table(displayName="Table1", ref=f"A1:{maxCol}{maxRow}")
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
                       showLastColumn=False, showRowStripes=True, showColumnStripes=True)

tab.tableStyleInfo = style

# Create a new workbook and add a worksheet with optimized write
newBook = openpyxl.Workbook(write_only=True)
newSheet = newBook.create_sheet()
newSheet.title = 'test'

for row in ws.rows:
    newSheet.append((cell.value for cell in row))

# Initialize headers and add to table
tab._initialise_columns()
for column, value in zip(tab.tableColumns, headers):
    column.name = value

# Add table
newSheet.add_table(tab)  # Warning here
newBook.save(f"C:\\testSaveDirec\\test.xlsx")

我已经阅读了有关以只写模式添加表格的文档,并相信我做得正确,但是当我尝试使用

newSheet.add_table(tab)
将表格添加到工作表时,它给了我警告:

warn("In write-only mode you must add table columns manually")

当我在保存文件后打开该文件时,该文件已损坏,并且 Excel 表示发现该文件有问题。

非常感谢任何帮助!

python excel openpyxl
1个回答
0
投票

更新 - 使用 win32com 模块修复。新代码:

import win32com.client

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 0
exc.Workbooks.Open(Filename=excelFile)

# Add headers
for idx, hd in enumerate(headers):
    exc.Cells(1, idx + 1).Value = hd

exc.ActiveSheet.UsedRange.Select()
exc.Selection.Columns.AutoFit()
exc.ActiveSheet.ListObjects.Add().TableStyle = "TableStyleMedium9"
exc.ActiveWorkbook.Save()

** 此代码用标题替换第一行,因为我的第一行是空白的,但我确信有方法可以插入带有标题的新第一行

© www.soinside.com 2019 - 2024. All rights reserved.