【Python实例学习】用Python的xlsxwriter模块,进行Excel表格插入图标的操作

# _*_ coding: utf-8 _*_
# 引入xlsxwriter模块。必须提前安装该模块
import xlsxwriter

# 使用xlsxwriter模块的Workbook方法,新建test20200121.xlsx,并将该表命名为excel_test
# 文件夹路径需要用左斜杠/。如果不写文件夹路径,就会存储到编译器默认路径。
excel_test = xlsxwriter.Workbook("D:/test20200121.xlsx")

# 为excel_test表格使用add_worksheet方法增加sheet标签。如果有中文,前面需要加u,比如u"1月"
sheet_one = excel_test.add_worksheet("1month")
sheet_two = excel_test.add_worksheet("2month")
sheet_three = excel_test.add_worksheet("3month")

# 添加样式,使用字典格式:bold加粗、border边框宽度、align水平对齐方式、valign垂直对齐方式、fg_color背景色、color字体颜色、text_wrap自动换行
format1 = excel_test.add_format({"bold": True})
format2 = excel_test.add_format({"border": 1})
format3 = excel_test.add_format({"align":"center"})
format4 = excel_test.add_format({"valign":"vcenter"})
format5 = excel_test.add_format({"fg_color":"C4C4C4"})
format6 = excel_test.add_format({"color":"FF0000"})
format7 = excel_test.add_format({"text_wrap":True})
format8 = excel_test.add_format({"bold": True,"align":"center"})
format9 = excel_test.add_format(
    {"bold": True,
    "border": 1,
    "align":"center",
    "valign":"vcenter",
    "fg_color":"C4C4C4",
    "color":"FF0000",
    "text_wrap":True}
)

# 修改列宽
sheet_one.set_column("B:B", 25)
sheet_one.set_column("C:C", 15)
sheet_two.set_column("A:C", 10)

# 设置表头,自建数据,使用列表格式
headings1 = ['id', 'programe language', 'ratings(%)']
data1 = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    ["Java", "C", "Python", "C++", "C#", "VB.NET", "JavaScript", "PHP"],
    [16.896, 15.773, 9.704, 5.574, 5.349, 5.287, 2.451, 2.405]
]

headings2 = [u'编号', u'排行', u'姓名']
data2 = [
    [1, 2, 3, 4, 5, 6, 7],
    [u'李大', u'陶二', u'恭三', u'麦四', u'柳五', u'钱六', u'商七'],
    [u'李沉舟', u'陶百窗', u'恭文羽', u'麦当豪', u'柳随风', u'钱山谷', u'商天良']
]

# 写入数据。sheet_one使用第一套数据,sheet_two使用第二套数据。
sheet_one.write_row("A1", headings1, format8)
sheet_one.write_column("A2", data1[0], format3)
sheet_one.write_column("B2", data1[1], format3)
sheet_one.write_column("C2", data1[2], format3)

sheet_two.write_row("A1", headings2, format9)
sheet_two.write_column("A2", data2[0], format3)
sheet_two.write_column("B2", data2[1], format3)
sheet_two.write_column("C2", data2[2], format3)

# 比较简单的插入数据和图片
sheet_three.write("B2", u"李四")
# 写入图片。# 文件夹路径需要用左斜杠/。如果不写文件夹路径,就会选择编译器默认路径的对应图片。
sheet_three.insert_image("C5", "D:/3.jpg")

# 插入图表
chart_col = excel_test.add_chart({"type":"line"})
chart_col.add_series(
    {
        "name": "=1month!$B$1",
        "categories": "=1month!$B$2:$B$9",
        "values": "=1month!$C$2:$C$9",
        "line": {"color":"red"}
    }
)

# 设置标题、X轴和Y轴的文字
chart_col.set_title({"name":u"2019年软件语言市场占有率"})
chart_col.set_x_axis({"name":u"软件语言名称"})
chart_col.set_y_axis({"name":u"占有率"})

chart_col.set_style(1)

# 选择图标的插入位置
sheet_one.insert_chart("A10",chart_col,{"x_offset":25,"y_offset":10})

# 关闭并保存Excel,必须有这段代码,否则上面所有代码将不会被保存。
excel_test.close()
发布了63 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/104080313