import openpyxl from wordcloud import WordCloud # 打开Excel文件 workbook = openpyxl.load_workbook('shu_ju.xlsx', read_only=True) # 获取第一个工作表 worksheet = workbook[workbook.sheetnames[0]] # 获取第一列数据 column_data = [cell.value for cell in worksheet['A']] # 将列表转换为字符串 text = ' '.join(str(cell) for cell in column_data) # 创建 WordCloud 对象 wordcloud = WordCloud(width=800, height=800, background_color='white', max_words=200, contour_width=3, contour_color='steelblue') # 生成云图 wordcloud.generate(text) # 保存云图到文件 wordcloud.to_file('yuntu.png')然后出现Traceback (most recent call last): File "G:\Projects\MediaPipe\chusheng.py", line 11, in <module> column_data = [cell.value for cell in worksheet['A']] File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\worksheet\worksheet.py", line 301, in __getitem__ cols = tuple(self.iter_cols(min_col, max_col)) AttributeError: 'ReadOnlyWorksheet' object has no attribute 'iter_cols'怎么解决
时间: 2024-03-17 19:46:27 浏览: 103
这个错误提示说明 `openpyxl` 库中的 `ReadOnlyWorksheet` 类没有实现 `iter_cols` 方法。你可以使用 `worksheet.columns` 属性来获取指定列的数据,然后使用列表推导式获取单元格的值,如下所示:
```
import openpyxl
from wordcloud import WordCloud
# 打开Excel文件
workbook = openpyxl.load_workbook('shu_ju.xlsx', read_only=True)
# 获取第一个工作表
worksheet = workbook[workbook.sheetnames[0]]
# 获取第一列数据
column_data = [cell.value for row in worksheet.iter_rows(values_only=True) for cell in row if cell.column == 1]
# 将列表转换为字符串
text = ' '.join(str(cell) for cell in column_data)
# 创建 WordCloud 对象
wordcloud = WordCloud(width=800, height=800, background_color='white', max_words=200, contour_width=3, contour_color='steelblue')
# 生成云图
wordcloud.generate(text)
# 保存云图到文件
wordcloud.to_file('yuntu.png')
```
这样你应该就可以成功读取 Excel 文件并生成词云了。
阅读全文