import pandas as pd file_path = "干支线装载率明细表(速运)-剔除后.xlsx" sheet_name = "装载数据" try: # 读取数据 loading_rate = pd.read_excel(file_path, usecols=["线路运行日期", "线路类型", "需求始发网点", "需求目的网点", "满载载量(旧)", "装载重量", "装载率分段(旧)", "线路里程(KM)", "交易渠道类型(T-2)"],sheet_name = {file_path[0:len(file_path)-5]}) loading_rate["线路里程(KM)"] = pd.to_numeric(loading_rate["线路里程(KM)"], errors='coerce') # 设置样式 styled_df = loading_rate.style \ .set_properties(**{'text-align': 'center'}) \ .set_table_styles([{'selector': 'td', 'props': [('min-width', '50px')]}]) \ .set_table_attributes('border="1" cellspacing="0" cellpadding="4"') # 写入数据 with pd.ExcelWriter("场地效益看板.xlsx", engine='openpyxl', mode='a', if_sheet_exists='replace') as writer: try: # 如果子表存在,则覆盖原子表 writer.book[sheet_name] writer.sheet = {ws.title:ws for ws in writer.book.worksheets} except KeyError: pass styled_df.to_excel(writer, sheet_name=sheet_name, index=False) print("完成清洗") except Exception as e: print("发生了异常:", e)帮我调试一下这段代码
时间: 2023-07-19 11:34:53 浏览: 161
根据你提供的代码,我发现有几个问题:
1. `writer.book[sheet_name]` 这行代码应该写成 `writer.book[sheet_name] = writer.book.create_sheet(sheet_name)`,这样才能创建新的工作表。
2. `writer.sheet = {ws.title:ws for ws in writer.book.worksheets}` 这行代码应该写成 `writer.sheets = {ws.title:ws for ws in writer.book.worksheets}`。
3. `pd.ExcelWriter` 的 `if_sheet_exists` 参数应该设置为 `replace`,而不是 `replace_sheet`。
下面是修改后的代码:
```python
import pandas as pd
file_path = "干支线装载率明细表(速运)-剔除后.xlsx"
sheet_name = "装载数据"
try:
# 读取数据
loading_rate = pd.read_excel(file_path,
usecols=["线路运行日期", "线路类型", "需求始发网点", "需求目的网点", "满载载量(旧)",
"装载重量", "装载率分段(旧)", "线路里程(KM)", "交易渠道类型(T-2)"],
sheet_name=sheet_name)
loading_rate["线路里程(KM)"] = pd.to_numeric(loading_rate["线路里程(KM)"], errors='coerce')
# 设置样式
styled_df = loading_rate.style \
.set_properties(**{'text-align': 'center'}) \
.set_table_styles([{'selector': 'td', 'props': [('min-width', '50px')]}]) \
.set_table_attributes('border="1" cellspacing="0" cellpadding="4"')
# 写入数据
with pd.ExcelWriter("场地效益看板.xlsx", engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
try:
# 如果工作表存在,则覆盖原工作表
writer.book[sheet_name] = writer.book.create_sheet(sheet_name)
except KeyError:
pass
writer.sheets = {ws.title: ws for ws in writer.book.worksheets}
styled_df.to_excel(writer, sheet_name=sheet_name, index=False)
print("完成清洗")
except Exception as e:
print("发生了异常:", e)
```
修改后的代码应该可以正常运行了。
阅读全文