programing

특성 오류: '워크시트' 개체에 'set_column' 특성이 없습니다.

css3 2023. 8. 18. 22:49

특성 오류: '워크시트' 개체에 'set_column' 특성이 없습니다.

오류가 발생하고 있습니다. 이 오류는...틀렸어.워크시트 개체는 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가 설치되어 있습니다.

제공되는 이유:AttributeError: 'Worksheet' object has no attribute 'write'

PC에 xlsxwriter를 설치하지 않았기 때문입니다.

사용할 수 있는 항목:

pip install xlsxwriter

그리고 그것은 효과가 있을 것입니다.

단일 열 범위에 오류가 있습니다.그들은 그래야 합니다.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()

출력: enter image description here

위의 코드를 사용하여 작동하는지 확인합니다.그렇지 않으면 XlsxWriter가 설치되지 않을 수 있으며 Pandas는 OpenPyXL로 기본 설정됩니다.

저도 같은 문제가 있었는데, 다음과 같은 문제가 해결되었습니다.

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

    # 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

언급URL : https://stackoverflow.com/questions/63493743/attributeerror-worksheet-object-has-no-attribute-set-column