【Python实例学习】用Python的xlsxwriter模块操作Excel表格,包括写入数据、样式设置、插入图片等

python来新建Excel,并插入数据。

1.首先,我们使用的是xlsxwriter模块,需要先安装。打开命令提示符,用pip进行安装。

pip install xlsxwriter  #python2

pip3 install xlsxwriter #python3

2.安装成功。

3.开始执行代码。

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

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

# 为excel_test表格使用add_worksheet方法增加sheet标签。因为有中文,所以前面加了u
sheet_one = excel_test.add_worksheet(u"1月")
sheet_two = excel_test.add_worksheet(u"2月")
sheet_three = excel_test.add_worksheet(u"3月")

# 添加样式,使用字典格式: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_two.set_column("A:C", 10)

# 设置表头,自建数据,使用列表格式
headings1 = ['id', 'programming 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")

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

猜你喜欢

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