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()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容