Link1133 2022-12-20 18:17 采纳率: 44.4%
浏览 16
已结题

xlwings分拆excel表格提示AttributeError: 'str' object has no attribute 'expand'

xlwings分拆excel表格提示AttributeError: 'str' object has no attribute 'expand'

下面是我的代码和excel表格,这种情况要怎么解决?

import xlwings as xw 
df = pd.read_excel("C:\\Users\\Link\\Desktop\\python数据分析期末报告\\xiugai.xlsx")
df["交易日期"] = pd.to_datetime(df["交易日期"])
df["年"]=df["交易日期"].dt.year
resultPath = 'C:\\Users\\Link\\Desktop\\python数据分析期末报告\\x.xlsx'
df.to_excel(resultPath,index = False)
file_path = 'C:\\Users\\Link\\Desktop\\python数据分析期末报告\\x.xlsx' 
sheet_name = 'sheet1' 
app = xw.App(visible=False,add_book=False)
workbook = app.books.open(file_path) 
worksheet = workbook.sheets[sheet_name] 
value = worksheet.range('A1').expand('年').value 
data = dict() 
for i in range(len(value)): 
    product_name = value[i][12] 
    if product_name not in data: 
        data[product_name] = [] 
    data[product_name].append(value[i]) 
for key,value in data.items(): 
    new_workbook = xw.books.add() 
    new_worksheet = new_workbook.sheets.add(key) 
    new_worksheet['A1'].value = worksheet['A1:H1'].value 
    new_worksheet['A2'].value = value 
    new_workbook.save('{}.xlsx'.format(key)) 
app.quit()
AttributeError                            Traceback (most recent call last)
Input In [21], in <cell line: 8>()
      6 workbook = app.books.open(file_path) 
      7 worksheet = workbook.sheets[sheet_name] 
----> 8 value = worksheet.range('A1').expand('年').value 
      9 data = dict() 
     10 for i in range(len(value)): 

File E:\Anaconda3\lib\site-packages\xlwings\main.py:2025, in Range.expand(self, mode)
   1999 def expand(self, mode='table'):
   2000     """
   2001     Expands the range according to the mode provided. Ignores empty top-left cells (unlike ``Range.end()``).
   2002 
   (...)
   2023     .. versionadded:: 0.9.0
   2024     """
-> 2025     return expansion.expanders.get(mode, mode).expand(self)

AttributeError: 'str' object has no attribute 'expand'

img

  • 写回答

1条回答 默认 最新

  • ShowMeAI 2022-12-20 18:34
    关注

    你在行 8 中将一个字符串作为参数传给了 expand 函数。

    望采纳

    你将 '年' 传递给函数作为一个字符串,但是 expand 函数期望的是一个模式参数,其中模式是 'table', 'down', 'right', 'up' 或 'left' 之一。

    如果你想要扩展区域以包括所有相邻的单元格,则可以将模式设置为 'table':

    value = worksheet.range('A1').expand('table').value
    

    或者,如果你想要仅扩展区域以包括下方的单元格,则可以将模式设置为 'down':

    value = worksheet.range('A1').expand('down').value
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月28日
  • 已采纳回答 12月20日
  • 创建了问题 12月20日

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值