python绘制流程甘特图并输出到Excel中
时间: 2024-10-13 10:15:57 浏览: 31
在Python中,虽然`matplotlib`库主要用于静态绘图,包括简单的甘特图,但它并不直接支持导出到Excel。不过我们可以借助第三方库`openpyxl`和`xlsxwriter`来实现这个功能。下面是一个简单的例子,演示如何绘制流程甘特图,并将其保存为Excel文件:
首先,安装必要的库:
```bash
pip install matplotlib openpyxl xlsxwriter
```
然后,使用`pandas`构建数据结构,模拟甘特图的数据:
```python
import pandas as pd
# 创建数据
tasks = {
'Task': ['Task1', 'Task2', 'Task3'],
'Start': [0, 2, 4],
'End': [6, 8, 10]
}
df_gantt = pd.DataFrame(tasks)
```
接下来,使用`mpl_toolkits`库里的`dateutil.relativedelta`模块对时间进行转换以便与`matplotlib`兼容:
```python
from datetime import datetime, timedelta
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
df_gantt['Start'] = df_gantt['Start'].apply(lambda x: datetime.now() + timedelta(days=x))
df_gantt['End'] = df_gantt['End'].apply(lambda x: datetime.now() + timedelta(days=x))
```
绘制甘特图:
```python
fig, ax = plt.subplots(figsize=(10, 5))
axins = inset_axes(ax, width="30%", height="30%", loc=3) # 嵌入子图
for _, row in df_gantt.iterrows():
ax.barh(row['Task'], row['End'] - row['Start'], left=row['Start'])
mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.5")
plt.yticks(rotation=90)
# 写入Excel
workbook = xlsxwriter.Workbook('gantt_chart.xlsx')
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.add_series({
'name': '=Sheet1!A2',
'categories': '=Sheet1!B:B',
'values': '=Sheet1!C:C'
})
chart.set_title({'name': 'Gantt Chart'})
worksheet.write('A1', 'Tasks')
worksheet.write_column('B1', df_gantt['Task'])
worksheet.write_column('C1', df_gantt['Start'].dt.strftime('%Y-%m-%d') + ' to ' + df_gantt['End'].dt.strftime('%Y-%m-%d'))
worksheet.insert_chart('E1', chart)
workbook.close()
```
最后,运行这段代码,你会得到一个甘特图并保存为名为`gantt_chart.xlsx`的Excel文件。
阅读全文