4-python library-xlwt or xlsxwriter excel table operation

The most common python publicity that those training institutions on the Internet do is to use Python to complete the automated excel office and get rid of repeated labor. I have not done this work, but I will use excel to record test data during automated testing, using the xlwt library Write excel

Once I need to sort the recorded data into a line chart, but it seems that I have not found the operation of drawing with xlwt. Later, I can find that using the xlsxwriter library can be achieved, so the two libraries xlwt and xlsxwriter are described below.

1. Add sheet

Create an excel file and add a sheet form

1.1 xlwt method
import xlwt

if __name__ == '__main__':
    excel_fd = xlwt.Workbook()
    sheet_fd = excel_fd.add_sheet("test1")  # 增加sheet

    excel_fd.save("./test.xls")  # 保存xls
1.2 xlsxwriter
import xlsxwriter

if __name__ == '__main__':
    excel_fd = xlsxwriter.Workbook("test.xlsx")
    sheet_fd = excel_fd.add_worksheet("test1")
    
    excel_fd.close()

2. Set the length and width

2.1 xlwt method

Set the width of each column

import xlwt

if __name__ == '__main__':
    excel_fd = xlwt.Workbook()
    sheet_fd = excel_fd.add_sheet("test1")  # 增加sheet

    sheet_fd.col(0).width = 200 * 40  # 设置第1列列宽
    sheet_fd.col(1).width = 200 * 15  # 设置第2列列宽
    sheet_fd.col(2).width = 200 * 15  # 设置第3列列宽

    excel_fd.save("./test.xls")  # 保存xls
    

Xlwt is not used to set the height of the line temporarily, but you can use the font size attribute in font and style to modify the line height

2.2 xlsxwriter

The xlsxwriter library can set the width of columns and the height of rows, but the units are different.

import xlsxwriter

if __name__ == '__main__':
    excel_fd = xlsxwriter.Workbook("test.xlsx")
    sheet_fd = excel_fd.add_worksheet("test1")
    sheet_fd.set_column(0, 0, 10)  # 设置第1列宽度
    sheet_fd.set_column(1, 1, 20)  # 设置第2列宽度
    sheet_fd.set_column(2, 2, 30)  # 设置第3列宽度
    sheet_fd.set_row(0, 10)  # 设置第1行高度
    sheet_fd.set_row(1, 20)  # 设置第2行高度
    sheet_fd.set_row(2, 30)  # 设置第3行高度
    
    excel_fd.close()

The set_columnfunction is used when setting the column , the first and second parameters are from the starting column and the ending column, and when setting the row, set_romthe parameter of one row is used .

3. Set font color, size, border, background color, center

Setting the color, size and other parameters of the font is the basic element of making a form, otherwise the form will have no emotion, so here are a few commonly used elements.

3.1 xlwt method

The Font style interface in xlwt is familiar with the above functions. Here, a set_style function is encapsulated for calling

The first parameter is the font color, the second parameter is the font size, the third parameter is whether the font is bold, the fourth parameter is the background color, and the fifth parameter is whether it is centered.

Of course, there are many other attributes that need to be extended by yourself.

def set_style(font_color, height, bold=False, pattern_color='', align='center'):
    style = xlwt.XFStyle()  # 初始化样式
    font = xlwt.Font()  # 为样式创建字体
    font.name = 'Times New Roman'
    font.bold = bold
    font.height = height
    font.colour_index = font_color

    borders = xlwt.Borders()  # 为样式创建边框
    borders.left = 0
    borders.right = 0
    borders.top = 0
    borders.bottom = 0

    alignment = xlwt.Alignment()  # 设置排列
    if align == 'center':
        alignment.horz = xlwt.Alignment.HORZ_CENTER
        alignment.vert = xlwt.Alignment.VERT_CENTER
    else:
        alignment.horz = xlwt.Alignment.HORZ_LEFT
        alignment.vert = xlwt.Alignment.VERT_BOTTOM

    if pattern_color != '':
        pattern = xlwt.Pattern()  # 一个实例化的样式类
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN  # 固定的样式
        pattern.pattern_fore_colour = xlwt.Style.colour_map[pattern_color]  # 背景颜色
        style.pattern = pattern

    style.font = font
    style.borders = borders
    style.alignment = alignment

    return style

The following example uses write to write input. The first parameter is the row, the second parameter is the column, and the third parameter is the input content. The following style can call the set_style interface packed above.

import xlwt

RED = 0x0A
GREEN = 0x11
BLACK = 0X7FFF


if __name__ == '__main__':
    excel_fd = xlwt.Workbook()
    sheet_fd = excel_fd.add_sheet("test1")  # 增加sheet

    sheet_fd.col(0).width = 200 * 40  # 设置第1列列宽
    sheet_fd.col(1).width = 200 * 15  # 设置第2列列宽
    sheet_fd.col(2).width = 200 * 15  # 设置第3列列宽

    sheet_fd.write(0, 0, "test1",
                   style=set_style(RED, 260, bold=True, align='', pattern_color='light_orange'))
    sheet_fd.write(0, 1, "test2",
                   style=set_style(GREEN, 260, bold=False, align='', pattern_color='gray25'))
    sheet_fd.write(1, 2, "test3",
                   style=set_style(BLACK, 460, bold=True, align='center'))

    excel_fd.save("./test.xls")  # 保存xls
3.2 xlsxwriter

Similar to the xlwt method, but the call_format is used in xlsxwriter.

We also set up a set_format interface to set the font format in the same way as above. The parameter filling format will be slightly different, but the same is similar, as follows:

import xlsxwriter

def set_format(excel_fd, font_color, height, bold=False, pattern_color='', align='center'):
    style = excel_fd.add_format({
        "fg_color": pattern_color,  # 单元格的背景颜色
        "bold": bold,  # 字体加粗
        "align": align,  # 对齐方式
        "font_color": font_color,  # 字体颜色
        "font_size": height  # 字体颜色
    })

    return style


if __name__ == '__main__':
    excel_fd = xlsxwriter.Workbook("test.xlsx")
    sheet_fd = excel_fd.add_worksheet("test1")

    sheet_fd.write(0, 0, "test1",
                   set_format(excel_fd, "red", 20, bold=True, align='', pattern_color='light_orange'))
    sheet_fd.write(0, 1, "test2",
                   set_format(excel_fd, "green", 30, bold=False, align='', pattern_color='gray25'))
    sheet_fd.write(1, 2, "test3",
                   set_format(excel_fd, "black", 40, bold=True, align='center'))

    excel_fd.close()

4. Merge cells

When making the table header, several cells will be merged into one

4.1 xlwt method
  • Parameters 1 and 2: start row and start col
  • Parameters 3 and 4: end row and end col
  • Parameter 5: Content
  • Parameter 6: style
sheet_fd.write_merge(3, 3, 4, 4,  "merge", set_style(0x7FFF, 320, bold=True))
4.2 xlsxwriter

In the same way as xlwt, the content is as follows:

  • Parameters 1 and 2: start row and start col
  • Parameters 3 and 4: end row and end col
  • Parameter 5: Content
  • Parameter 6: cell_format style
sheet_fd.merge_range(3, 3, 4, 4, "merge", set_format(0x7FFF, 320, bold=True))

5. Draw a line chart

The only way to draw a line chart here is xlsxwriter

import xlsxwriter

if __name__ == '__main__':
    excel_fd = xlsxwriter.Workbook("test.xlsx")
    sheet_fd = excel_fd.add_worksheet("test1")
    sheet_fd.write(0, 0, "X")
    sheet_fd.write(1, 0, 1)
    sheet_fd.write(2, 0, 2)
    sheet_fd.write(3, 0, 3)
    sheet_fd.write(4, 0, 4)

    sheet_fd.write(0, 1, "Y")
    sheet_fd.write(1, 1, 4)
    sheet_fd.write(2, 1, 5)
    sheet_fd.write(3, 1, 5)
    sheet_fd.write(4, 1, 3)

    chart_fd = excel_fd.add_chart({'type': 'line'})   # 添加折线图
    chart_fd.set_title({'name': 'XY'})  # 添加图标名字
    chart_fd.set_x_axis({'name': '=' + 'test1' + '!$A$1'})  # 添加X名字(test1为sheet表)
    chart_fd.set_y_axis({'name': '=' + 'test1' + '!$B$1'})  # 添加Y名字(test1为sheet表)

    chart_fd.add_series({   # 给图表设置格式,填充内容
        'marker': {'type': 'diamond'},
        'name': ['test1', 1, 0],
        'categories': ['test1', 1, 0, 4, 0],
        'values': ['test1', 1, 1, 4, 1],  # 从第几行到第几行的内容(test1为sheet表)
    })
    sheet_fd.insert_chart(1, 2, chart_fd)

    excel_fd.close()

Reference
https://www.cnblogs.com/brightbrother/p/8671077.html

Published 106 original articles · praised 76 · 130,000 visits +

Guess you like

Origin blog.csdn.net/Creator_Ly/article/details/104479320