excel 属性错误:“Worksheet”对象没有属性“set_column”

sdnqo3pr  于 2023-04-22  发布在  其他
关注(0)|答案(4)|浏览(1116)

我得到了一个错误,似乎...错误。因为当然工作表对象有set_column()作为一个函数,它在文档中。我可能做了一些愚蠢的事情,比如删除括号。
下面是错误:

Traceback (most recent call last):
  File "scrubaddresses.py", line 137, in <module>
    run()
  File "scrubaddresses.py", line 118, in run
    format_col_width(worksheet)
  File "scrubaddresses.py", line 24, in auto_format_cell_width
    ws.set_column('B:C', 20)
AttributeError: 'Worksheet' object has no attribute 'set_column'

这是我可笑的导入。配置是一些常量,控制器有一些帮助函数。

from smartystreets_python_sdk import StaticCredentials, exceptions, Batch, ClientBuilder
from smartystreets_python_sdk.us_street import Lookup as StreetLookup
from pathlib import Path
import pandas as pd
import numpy as np
import config
from controller import getExcel, clean

相关函数:

def format_col_width(ws):
    ws.set_column('B:C', 20)
    ws.set_column('D', 1)
    ws.set_column('E', 20)

正在传递的ws来自何处:

df1 = df.replace(np.nan, '', regex=True)
            print(df1)

            df1.to_excel(writer, sheet, index = False, engine='xlsxwriter')
            worksheet = writer.sheets[sheet]
            format_col_width(worksheet)

我忘记导入什么了吗?Xlsxwriter已安装。

lrpiutwd

lrpiutwd1#

它给出的理由是:AttributeError: 'Worksheet' object has no attribute 'write'
这是因为您没有在PC上安装xlsxwriter。
您可以用途:

pip install xlsxwriter

它会工作伊萨。

lbsnaicq

lbsnaicq2#

我也遇到了同样的问题,以下方法对我有效:

def format_col_width(ws):
    ws.column_dimensions['B'].width = 20
    ws.column_dimensions['C'].width = 20
    ws.column_dimensions['D'].width = 1
    ws.column_dimensions['E'].width = 20
6yjfywim

6yjfywim3#

单列范围中有一个错误。它们应该是D:D而不是D,因为即使它们相同,该方法也需要开始和结束列。
经过这样的修改,代码应该可以工作:

import pandas as pd

def format_col_width(ws):
    ws.set_column('B:C', 20)
    ws.set_column('D:D', 1)
    ws.set_column('E:E', 20)

df = pd.DataFrame({'Data1': [10, 20, 30, 20, 15, 30, 45]})

writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

format_col_width(worksheet)

writer.save()

输出:

尝试上面的代码,看看它是否工作。如果它不工作,那么XlsxWriter可能没有安装,Pandas默认为OpenPyXL。

nxagd54h

nxagd54h4#

# monkey path :) -- https://stackoverflow.com/questions/74844262/how-can-i-solve-error-module-numpy-has-no-attribute-float-in-python
    # as of 2023/04/21
    # AttributeError: module 'numpy' has no attribute 'float'
    np.float = float  
    writer = pd.ExcelWriter('test.xlsx') 
    df.to_excel(writer, sheet_name='Sheet1', index=False, na_rep='NaN')
    for column in df:
        column_length = max(df[column].astype(str).map(len).max(), len(column))
        col_idx = df.columns.get_loc(column)
        #writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_length)  <-- set_column deprecated
        writer.sheets['Sheet1'].column_dimensions[chr(65+col_idx)].width = column_length + 5   # add some extra space {5 here} to have a better look

相关问题