from openpyxl import load_workbook import unicodedata # 指定表格文件名列表 filenames = ['file1.xlsx', 'file2.xlsx', 'file3.xlsx'] # 使用列表推导式读取多个表格 workbooks = [load_workbook(filename) for filename in filenames] # 遍历每个工作表 for workbook in workbooks: for sheetname in workbook.sheetnames: sheet = workbooks[sheetname] # 遍历每个单元格 for row in sheet.iter_rows(): for cell in row: # 判断单元格是否为字符串类型 if isinstance(cell.value, str): # 将全角字符转换为半角字符 cell.value = unicodedata.normalize('NFKC', cell.value) # 保存修改后的 Excel 文件 for i, wb in enumerate([wb1, wb2, wb3]): wb.save(filenames[i])
时间: 2024-01-16 09:02:20 浏览: 69
解决python执行较大excel文件openpyxl慢问题
5星 · 资源好评率100%
以下是经过修正后的代码:
```python
import unicodedata
from openpyxl import load_workbook
# 指定表格文件名列表
filenames = ['file1.xlsx', 'file2.xlsx', 'file3.xlsx']
# 使用列表推导式读取多个表格
workbooks = [load_workbook(filename) for filename in filenames]
# 遍历每个工作表
for workbook in workbooks:
for sheetname in workbook.sheetnames:
sheet = workbook[sheetname]
# 遍历每个单元格
for row in sheet.iter_rows():
for cell in row:
# 判断单元格是否为字符串类型
if isinstance(cell.value, str):
# 将全角字符转换为半角字符
cell.value = unicodedata.normalize('NFKC', cell.value)
# 使用循环存储多个表格
for i, workbook in enumerate(workbooks):
workbook.save(filenames[i])
```
修正后,代码中的问题包括:
1. `from openpyxl import load_workbook import unicodedata` 这一行代码中应该将 `import unicodedata` 移到 `from openpyxl import load_workbook` 的下一行。
2. `workbooks.sheetnames` 应该修改为 `workbook.sheetnames`,因为在遍历时,变量名 `workbook` 代表的是一个具体的 Excel 表格对象。
3. 将保存 Excel 文件的代码移动到循环之外,以便遍历每个 Excel 表格之后再进行保存。
阅读全文