如何解决问题:保存时出现“预期<class 'openpyxl.styles.fills.Fill'>”

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

每次保存文件时都会出现错误:

 raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'openpyxl.styles.fills.Fill'>

然后无法再访问已保存的文件(当我手动打开它时)

open and load succesfully the file with openpyxl library:
book = openpyxl.load_workbook(r'C:\Users\shoshana\PycharmProjects\pandas\doh_golmi.xlsx')

保存方式:

book.save(r'C:\Users\shoshana\PycharmProjects\pandas\doh_golmi_2.xlsx')

然后

import openpyxl
......
openpyxl.load_workbook(r'C:\Users\shoshana\PycharmProjects\pandas\doh_golmi.xlsx')
....
book.save(r'C:\Users\shoshana\PycharmProjects\pandas\doh_golmi_2.xlsx')

当然希望能够保存我在文件中所做的更改,并在手动打开文件时访问该文件。

python-3.x openpyxl
4个回答
2
投票

我遇到了同样的错误,并且我错误地使用了 cell.fill 。换句话说,我正在做类似的事情

import openpyxl
openpyxl.load_workbook(r'C:\some\file.xlsx')
...
yellow = openpyxl.styles.colors.Color(rgb='FFFF00')
cell.fill = yellow 
...
book.save(r'C:\some\file.xlsx')

上面是不正确的,你必须使用PatternFill(见下文)

import openpyxl
openpyxl.load_workbook(r'C:\some\file.xlsx')
...
yellow = openpyxl.styles.colors.Color(rgb='FFFF00')
filling = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=color)
cell.fill = filling
...
book.save(r'C:\some\file.xlsx')

0
投票

我也遇到了类似的问题,但无法加载文件。 唯一的方法是手动打开它,保存它并加载它。

我的解决方法是使用 libreoffice 转换文件:

我在我的 jupyter 笔记本中运行了这个命令行:

!libreoffice --convert-to xls 'my_file.xlsx'

这会创建一个名为 my_file.xls 的新 xls(无 x)文件,现在可以使用 pandas 打开该文件。

import pandas as pd
df = pd.read_excel('my_file.xls')

0
投票

我没有足够的积分来发表评论,所以我会这样做:

JDArango 的答案有效,但请注意 xls 有更严格的行和列限制。当行/列太多时,转换只会将它们丢弃而不给出任何警告。


0
投票

我在 pandas 中也遇到了同样的问题。我尝试在 Windows 中使用以下脚本将所有 Excel 文件转换为 CSV。

$excel.Visible = $false

$folderPath = ""
$csvFolderPath = ""

# Create the output directory if it doesn't exist
if (-Not (Test-Path -Path $csvFolderPath)) {
    New-Item -ItemType Directory -Path $csvFolderPath
}

# Get all .xlsx files recursively
$files = Get-ChildItem -Path $folderPath -Recurse -Filter *.xlsx

foreach ($file in $files) {
    # Create the directory structure in the output folder
    $relativePath = $file.FullName.Substring($folderPath.Length)
    $outputPath = Join-Path $csvFolderPath -ChildPath (Split-Path $relativePath -Parent)
    if (-Not (Test-Path -Path $outputPath)) {
        New-Item -ItemType Directory -Path $outputPath
    }

    # Convert the .xlsx file to .csv
    $workbook = $excel.Workbooks.Open($file.FullName)
    $csvPath = Join-Path $outputPath -ChildPath ($file.BaseName + ".csv")
    $workbook.SaveAs($csvPath, 6)  # 6 corresponds to xlCSV
    $workbook.Close($false)
    Write-Host "Converted $($file.FullName) to $csvPath"
}

$excel.Quit()

注意:我的子文件夹中有 Excel 文件。

另一个有用的答案线程位于 GitHub 上。我尝试过这个方法,但它对我不起作用。这可能对某人有帮助。

谢谢。

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