Operation Excel files

Disclaimer: This article is CSDN blogger "jie_ming514 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/m1090760001/article/details/103113825

Python write Excel files

First, the basic concept of
two, write Excel
Third, set the style
Fourth, real
V. Related Links

 

First, the basic concepts
in Excel mainly related to three concepts: Workbooks, Sheets, Cells. Wherein excel sheet is a Workbook; Sheet worksheet is a page table; Cell is a simple grid. Usually read and write Excel substantially three steps as follows: Open Workbook, positioning Sheet, operation Cell. Read and write the following points were introduced a few common approach of python.

Second, write Excel
Here we use a case study to demonstrate the process of Python written in Excel. A simulated student information, student information is written to an Excel file.

————————————————


Import library xlwt
Import xlwt
. 1
without xlwt library, then the library can be used to import pip:

the install xlwt PIP
. 1
acquires a Workbook, to set the encoding set "UTF-. 8"
work_book = xlwt.Workbook (encoding = "UTF-. 8")
. 1
generates a Sheet Workbooks in the
Worksheet = work_book.add_sheet (SHEET_NAME)
. 1
recording write into the cell
# row representing lines, COL for column, data representative of the contents to fill
worksheet.write (row, COL, data)
. 1
2
save to save the file in the Workbook
work_book.save (self.filename)
. 1
Third, styling
However, in the actual scene, far more than the production of Excel data is written so simple, sometimes in order to achieve beautiful, it involves complex table style. E.g:

Set the font, font size, font color, text placement, bold, italic, etc.
merge cells, rows, merge, merge column, and region merging
set the background color
to set the border properties
set the line width
below us one by one to demonstrate how to set the table style

Set the font
style = xlwt.XFStyle () # initialize style
font = xlwt.Font () # create the font style
font.name = "blackbody" # set the font to "black body", the default is "Arial"
font.height = 100 # set the font size to 100, the default is 200
. Font.Bold = True # whether the font is bold
font.underline = True # underscore
font.italic = True # italics
style.font = font # styled
worksheet.write (row, col, data, style) # write pattern data tape
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
merged cell are consolidated, and the combined column region merging
# merge from (0,0) to the cell (0,2) unit cells, cells of the first row and three merged cell
worksheet.write_merge (0, 0, 0, 2, "Hello World")
# line combined with other styles and
worksheet.write_merge (0, 0, 0, 2, "Hello World", style)
# merge from (0,0) to the cell (2,0) cells and three cells in the first column were combined
worksheet.write_merge (0, 0, 2, 0, "Hello World")
# merge from (0,0) to the cell (2,2) cells, and merging the first row 3 of 9 * 3 cells region
worksheet.write_merge (0, 0, 2, 2, "Hello World")
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
set the background color
pattern = xlwt.Pattern () # example of a style class
pattern.pattern = xlwt.Pattern .SOLID_PATTERN # fixed pattern
pattern.pattern_fore_colour = xlwt.Style.colour_map [ 'yellow'] # background color
style.pattern = pattern
worksheet.write (Row, COL, data, style) # write pattern data tape
. 1
2
. 3
. 4
. 5
set the border attribute
borders = xlwt.Borders () # to create the border style, border no default
borders.left = 1 # set left border width. 1
borders.right. 1 =
borders.top. 1 =
=. 1 borders.bottom
style.borders = Borders
worksheet.write (Row, COL, Data, style) # write pattern data tape
. 1
2
. 3
. 4
. 5
. 6
. 7
setting the line width of
the width of the column provided #
worksheet.col (i ) .width = 150 * 30
1
2
Fourth, real
Here we demonstrate an actual case, use the form below xlwt library written information:

----------------
Disclaimer: This article is CSDN blogger "jie_ming514 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/m1090760001/article/details/103113825

 

 

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

写# excel
import xlwt


class WriteExcel:

# 初始化
def __init__(self, filename, sheet_name):
self.work_book = xlwt.Workbook(encoding="UTF-8")
self.worksheet = self.work_book.add_sheet(sheet_name)
self.filename = filename
self.row = 0

# 保存Excel
def save(self):
self.work_book.save(self.filename)

# Set the style
DEF set_style (Self, name, height, Bold = False, format_str = '', align = left = 'Center'):
style = xlwt.XFStyle () # initialize style
font = xlwt.Font () # Create a font style
font.name = name # font
. Font.Bold = Bold
font.height height =

borders = xlwt.Borders () # Create a style for the border
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1

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

style.font = font
style.borders = borders
style.num_format_str = format_str
style.alignment = alignment
return style

Set Title # format
DEF set_title_style (Self):
return self.set_style ( 'black body', 300, bold = True, format_str = '')

# Set the header format
DEF set_head_style (Self):
head_style = self.set_style ( 'Times New Roman', 220, Bold = True, format_str = '')
pattern xlwt.Pattern = () # an instantiated class style
pattern .pattern = xlwt.Pattern.SOLID_PATTERN # fixed pattern
pattern.pattern_fore_colour = xlwt.Style.colour_map [ 'yellow'] # background color
head_style.pattern pattern =
return head_style

# Format detail lines
DEF set_default_style (Self):
return self.set_style ( 'Times New Roman', 200 is, Bold = False, format_str = '', align = left = 'right')

# 添加标题
def add_title(self, title):
self.worksheet.write_merge(0, 0, 0, 2, title, self.set_title_style())
self.row += 1

# Write file header
DEF add_head (Self, Key, value):
# write into cell
self.worksheet.write (self.row, 0, Key)
self.worksheet.write (self.row,. 1, value )
self.row +. 1 =

# 写入明细
def add_list(self, table_head, table_detail):
self.row += 1
for i, value in enumerate(table_head):
self.worksheet.write(self.row, i, value, self.set_head_style())
self.worksheet.col(i).width = 150 * 30
for rows in table_detail:
self.row += 1
for i, key in enumerate(rows):
self.worksheet.write(self.row, i, rows[key], self.set_default_style())


if __name__ == "__main__":
list_head = ["学号", "姓名", "性别"]
list_detail = [{"student_id": "1001", "name": "张三", "sex": "男"},
{"student_id": "1002", "name": "李四", "sex": "女"},
{"student_id": "1003", "name": "王五", "sex": "男"}]

writeExcel = WriteExcel ( "writeExcel.xlsx", " Student Information")
writeExcel.add_title ( "XX students in the class information table")
writeExcel.add_head ( "School name:", "A School")
writeExcel.add_head ( "class name: "," B class system ")
writeExcel.add_head (" number: "," 50 ")
writeExcel.add_list (list_head, list_detail)
writeExcel.save ()

Guess you like

Origin www.cnblogs.com/LukeLiu/p/11906118.html