data.xlsx
Month | Sales | Profit | Market Share |
---|---|---|---|
Jan | 200 | 50 | 20% |
Feb | 250 | 60 | 25% |
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.chart import (
Reference,
BarChart,
PieChart,
LineChart,
AreaChart,
ScatterChart,
RadarChart,
Series
)
# 1. 读取Excel数据
file_path = 'data.xlsx'
df = pd.read_excel(file_path)
# 2. 创建Excel工作簿并写入数据
wb = Workbook()
ws = wb.active
# 将DataFrame数据写入工作表
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
# 3. 生成柱状图(Sales数据)
bar_chart = BarChart()
data = Reference(ws, min_col=2, min_row=2, max_row=len(df) + 1) # Sales列数据
categories = Reference(ws, min_col=1, min_row=2, max_row=len(df) + 1) #