当前位置: 首页 > 工具软件 > WriteExcel > 使用案例 >

python3--实战--写入excel文件基本操作

易宣
2023-12-01

python3–实战–写入excel文件基本操作

源码如下:

# -*- coding: utf-8 -*-

import xlwt

def set_style(font_name, font_height, bold=False):
    style = xlwt.XFStyle()  # 初始化样式

    font = xlwt.Font()  # 为样式创建字体
    font.name = font_name  # 'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = font_height

    borders = xlwt.Borders()
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1

    style.font = font
    style.borders = borders

    return style

# 写excel
def write_excel(output_path):
    f = xlwt.Workbook() # 创建工作簿
    
    sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)  # 创建sheet
    row0 = [u'序号',u'源代码项目名称',u'高危漏洞(个)',u'中危漏洞(个)',u'低危漏洞(个)',u'漏洞合计(个)']
    column0 = ['1','2','3']
    projectname = ["TB_HangCloud_iam-management","TB_DemoCloud_rocket2-web","TB_HangCloud_FrontEnd_lianlianloanApp"]
    num1 = ["0","0","0"]
    # 生成第一行
    for i in range(0, len(row0)):
        #sheet1.write(m, n, row0[i])当中的m为行数位置,n为列数的位置,row0[i]为需要写入的列表个数
        #参考:https://jingyan.baidu.com/article/f79b7cb33dd6e09145023e6f.html
        sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))
    
    #生成第一列
    for j in range(0,len(column0)):
        sheet1.write(j+1, 0, column0[j], set_style('Times New Roman', 220, True))
    
    #生成第二列
    for k in range(0,len(projectname)):
        sheet1.write(k+1, 1, projectname[k], set_style('Times New Roman', 220, True))
    
    #生成第三列
    for k in range(0,len(num1)):
        sheet1.write(k+1, 2, num1[k], set_style('Times New Roman', 220, True))
    
    #生成第四列
    for k in range(0,len(num1)):
        sheet1.write(k+1, 3, num1[k], set_style('Times New Roman', 220, True))
    
    #生成第五列
    for k in range(0,len(num1)):
        sheet1.write(k+1, 4, num1[k], set_style('Times New Roman', 220, True))
    
    #生成第六列
    for k in range(0,len(num1)):
        sheet1.write(k+1, 5, num1[k], set_style('Times New Roman', 220, True))
            
    f.save(output_path)
    
if __name__ == '__main__':
    write_excel('D:/demo5.xls')  # 保存文件.这里如果是.xlsx的话会打不开

运行结果,打开demo5.xls,显示如下内容:

序号	源代码项目名称	                           高危漏洞(个)	      中危漏洞(个)	低危漏洞(个)	漏洞合计(个)
1	TB_HangCloud_iam-management	                0	              0	            0	            0
2	TB_DemoCloud_rocket2-web	                0	              0	            0	            0
3	TB_HangCloud_FrontEnd_lianlianloanApp	    0	              0	            0	            0

 类似资料: