xlswriter生成饼状图总结

1.xlswriter简介

点击官方文档了解更多
首先安装

$ pip install XlsxWriter

开始使用

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')#文件的名称
worksheet = workbook.add_worksheet('新sheet')#新增sheet
worksheet.write('A1', 'Hello world')#在A1格子里写入数据
workbook.close()

如果不想新增sheet,二是在原有sheet上操作,可能会用到下面的API:

workbook.worksheets()

worksheets()Return a list of the worksheet objects in the workbook.
| Return type: | A list of worksheet objects. |
The worksheets() method returns a list of the worksheets in a workbook. This is useful if you want to repeat an operation on each worksheet in a workbook:

for worksheet in workbook.worksheets():
    worksheet.write('A1', 'Hello')

或者

workbook.get_worksheet_by_name()

get_worksheet_by_name(name)
Return a worksheet object in the workbook using the sheetname.
| Parameters: | name (string) – Name of worksheet that you wish to retrieve. |
| Return type: | A worksheet object. |
The get_worksheet_by_name() method returns the worksheet or chartsheet object with the the given name or None if it isn’t found:

2.xlswriter写入数据

写入数据这块是最麻烦的。首先需要明确xlswriter关于excel单元格的两种标注方法

  • A1,G9 这种写法是标准的excel标注法,A-G 分别代表1-7列,1-9是1-9行
  • 0,3 这种是数组下标类似的标注法,0,3就代表第一行第四列(0代表第一)

2.1基础的单格写入

写入单个单元格:
worksheet1.write('A1', 123)
或者:
worksheet.write(0, 0, 'Hello')

2.2按行、列写入:

write_row(row, col, data[, cell_format])
data = ('Foo', 'Bar', 'Baz')

# Write the data to a sequence of cells.
worksheet.write_row('A1', data) 
###另一种写法:
worksheet.write_row(0, 0, data)
##按行写入,会依次写在传入的起点坐标同行的几个单元格
# The above example is equivalent to:
worksheet.write('A1', data[0])
worksheet.write('B1', data[1])
worksheet.write('C1', data[2])

按列写入如下:

write_column(row, col, data[, cell_format])
data = ('Foo', 'Bar', 'Baz')

# Write the data to a sequence of cells.
worksheet.write_column('A1', data)

# The above example is equivalent to:
worksheet.write('A1', data[0])
worksheet.write('A2', data[1])
worksheet.write('A3', data[2])

3.绘制图表

在excel里插入图表,图表的数据来源必须是excel表单中的数据,而不是程序里的数据,这就比较麻烦了,所以必须先写入数据
步骤如下:

  • 准备好要写入的数据
  • 写入数据
  • workbook新增chart对象
  • 为chart设置数据源
  • 设置chart参数、格式
  • 添加chart到sheet里

其中添加数据源add_series这个方法比较复杂,详细描述如下

## chart.add_series()

使用方法
chart.add_series({
    'categories': '=Sheet1!$A$1:$A$5',
    'values':     '=Sheet1!$B$1:$B$5',
    'line':       {'color': 'red'},
})

#其中坐标的标注还可以以数组的形式,这里描述的是一块区域,从左上角读取到右下角,顺序如下
#     [sheetname, first_row, first_col, last_row, last_col]
chart.add_series({
    'categories': ['Sheet1', 0, 0, 4, 0],
    'values':     ['Sheet1', 0, 1, 4, 1],
    'line':       {'color': 'red'},
})



The series options that can be set are:

*   `values`: 要显示的数据是什么

*   `categories`: This sets the chart category labels. The category is more or less the same as the X axis. In most chart types the `categories` property is optional and the chart will just assume a sequential series from `1..n`. 显示数据的标签是什么,默认从1-n


*   `data_labels`: Set data labels for the series. See [Chart series option: Data Labels](http://xlsxwriter.readthedocs.io/working_with_charts.html#chart-series-option-data-labels).

下面是官方的三个例子

import xlsxwriter

workbook = xlsxwriter.Workbook('chart_pie.xlsx')

worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})

# Add the worksheet data that the charts will refer to.准备数据源
headings = ['Category', 'Values']
data = [
    ['Apple', 'Cherry', 'Pecan'],
    [60, 30, 10],
]
#写入数据
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])

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

# Configure the series. Note the use of the list syntax to define ranges:
chart1.add_series({
    'name':       'Pie sales data',
    'categories': ['Sheet1', 1, 0, 3, 0],
    'values':     ['Sheet1', 1, 1, 3, 1],
})

# Add a title.
chart1.set_title({'name': 'Popular Pie Types'})

# Set an Excel chart style. Colors with white outline and shadow.
chart1.set_style(10)

# Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10})

#######################################################################
#
# Create a Pie chart with user defined segment colors.
#

# Create an example Pie chart like above.
chart2 = workbook.add_chart({'type': 'pie'})

# Configure the series and add user defined segment colors.
chart2.add_series({
    'name': 'Pie sales data',
    'categories': '=Sheet1!$A$2:$A$4',
    'values':     '=Sheet1!$B$2:$B$4',
    'points': [
        {'fill': {'color': '#5ABA10'}},
        {'fill': {'color': '#FE110E'}},
        {'fill': {'color': '#CA5C05'}},
    ],
})

# Add a title.
chart2.set_title({'name': 'Pie Chart with user defined colors'})

# Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('C18', chart2, {'x_offset': 25, 'y_offset': 10})

#######################################################################
#
# Create a Pie chart with rotation of the segments.
#

# Create an example Pie chart like above.
chart3 = workbook.add_chart({'type': 'pie'})

# Configure the series.
chart3.add_series({
    'name': 'Pie sales data',
    'categories': '=Sheet1!$A$2:$A$4',
    'values':     '=Sheet1!$B$2:$B$4',
})

# Add a title.
chart3.set_title({'name': 'Pie Chart with segment rotation'})

# Change the angle/rotation of the first segment.
chart3.set_rotation(90)

# Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('C34', chart3, {'x_offset': 25, 'y_offset': 10})

workbook.close()

4.与pandas结合使用

pandas 可以很方便的 使用 toexcel方法把数据导出到excel的sheet里,但是这样并不能指定导出的区域,如果想结合着使用,可以先使用pandas导出数据,然后利用xlswriter来接着读写数据。
其中怎么来获得toexcel生成的文件的workbook呢,方法是:

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_chart.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

下面是一个实用的列子:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_chart.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

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

# Configure the series of the chart from the dataframe data.
chart.add_series({'values': '=Sheet1!$B$2:$B$8'})

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

# Close the Pandas Excel writer and output the Excel file.
writer.save()

你可能感兴趣的:(xlswriter生成饼状图总结)