📌  相关文章
📜  Python | 使用XlsxWriter模块在Excel工作表中绘制饼图(1)

📅  最后修改于: 2023-12-03 15:19:02.905000             🧑  作者: Mango

Python | 使用XlsxWriter模块在Excel工作表中绘制饼图

XlsxWriter是一个用于创建Excel XLSX文件的Python模块。它可以在Excel工作表中创建丰富的格式。本文将介绍如何在Excel工作表中创建饼图。

步骤
  1. 安装XlsxWriter模块:

    !pip install XlsxWriter
    
  2. 创建Excel xlsx文件:

    import xlsxwriter
    
    workbook = xlsxwriter.Workbook('chart.xlsx')
    worksheet = workbook.add_worksheet()
    
  3. 创建饼图:

    chart = workbook.add_chart({'type': 'pie'})
    
    # Add data to chart
    chart.add_series({
        'name': 'Sales data',
        'categories': ['Sheet1', 1, 0, 5, 0],
        'values': ['Sheet1', 1, 1, 5, 1],
    })
    
    # Add a title to the chart
    chart.set_title({'name': 'Sales data by region'})
    
    # Insert the chart into the worksheet
    worksheet.insert_chart('B7', chart)
    
  4. 关闭Excel文件:

    workbook.close()
    
代码

完整的代码:

import xlsxwriter

# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

# Add some data.
worksheet.write('A1', 'Region')
worksheet.write('B1', 'Sales')
worksheet.write('A2', 'North')
worksheet.write('A3', 'South')
worksheet.write('A4', 'East')
worksheet.write('A5', 'West')
worksheet.write('B2', 100)
worksheet.write('B3', 200)
worksheet.write('B4', 150)
worksheet.write('B5', 75)

# Create a chart object.
chart = workbook.add_chart({'type': 'pie'})

# Add data to chart.
chart.add_series({
    'name': 'Sales data',
    'categories': ['Sheet1', 1, 0, 4, 0],
    'values': ['Sheet1', 1, 1, 4, 1],
})

# Add a title to the chart.
chart.set_title({'name': 'Sales data by region'})

# Insert the chart into the worksheet.
worksheet.insert_chart('B7', chart)

# Close the workbook.
workbook.close()
结论

XlsxWriter模块使Python程序员能够在Excel工作表中创建丰富的格式,包括饼图、折线图、散点图和条形图等。在本文中,我们展示了如何使用XlsxWriter模块在Excel工作表中创建饼图。