Flanders blog: https: //www.cnblogs.com/meilong/p/cao-zuoexcel-mo-kuaiopenpyxl.html
1 Installation
pip install openpyxl if not installed, specify the installation source to install pip install -i https://pypi.douban.com/simple openpyxl if excel there are pictures (jpeg, png, bmp, ... ), you need to install Image processing modules pip install pillow
2 excel write
Import Workbook openpyxl from # instantiate an object wb = Workbook () # create the workbook, the name is Shanghai, a Shanghai if only to write a default to the last workbook wb1 = wb.create_sheet ( 'Shanghai') # Create a workbook, workbooks in the first place wb2 = wb.create_sheet ( 'Guangdong', 0) # get the current work workbook the AWB = wb.active # to work not to change the name awb.title = "Guangdong" # write Excel data, you can write a function table # write data to the ability to work in guangdong book # write data into a cell awb [ 'A4'] = 'Cantonese cuisine' # write data to the third line of the first four cells in awb.cell (row = 3, column = 4 , value = " Fujian Cantonese eat") # append write the entire line awb.append ([ 'shrimp dumpling', 'Claw', 'goose']) # can be recycled written to the file for I in Range (10): awb.append ([1,2,3,4]) # write function table: AWB [ 'A16'] = "the SUM = (A6: A15) " # save the file wb.save ( 'city .xlsx')
excel read data
# Read files from openpyxl Import load_workbook # instantiate an object wb = load_workbook ( 'city .xlsx', READ_ONLY = False, DATA_ONLY = True) # Get all the workbook name # Print (wb.sheetnames) # get the workbook objects wb1 = WB [ 'Guangdong'] # if contents of the cell, but read out is None, the need to manually save the file open it, read, # reading function of the cell, the need to = True DATA_ONLY A4 = . WB1 [ "A4"] value # None A5 = wb1.cell (row =. 5, column =. 1) .Value # acquired data of all the lines, is a generator generator row = wb1.rows for in R & lt row: # r is the target data for each line, is in the form of tuples Print () for L in r: # L each data cell Print (l.value, End = '\ T') # Get all columns, is a generator COL = wb1.columns for C in COL: Print () for I in C: Print (i.value, End = '\ T') # total number of rows Print (wb1.max_row) # total number of column data print (wb1.max_column)
When reading the table should be noted:
Gets rows and columns
sheet.rows as generator, which is data for each row, each row consists of a tuple package.
sheet.columns similar, but there is and each tuple is the cell of each column. When you need to read the column read_only = False, or do not write, the default is False
When acquiring the rows or columns, the index can not be used to fetch data for a particular row, because sheel.rows is a generator, but the generator may be turned into a strong list, list (sheet.rows) [2] This allows to take the data line 3
When the reading table with a table function:
When reading data_only = True need to add this number is returned B9 read, if not this parameter will be returned formula itself '= AVERAGE (B2: B8)'
Set cell style --Style
First import the necessary classes from openpyxl.styles import Font, colors, Alignment
Respectively related to the specified font, color, and alignment.
Font:
bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.RED, bold=True) sheet['A1'].font = bold_itatic_24_font
Alignment:
Aligment cell is used as the properties specified herein centered vertically and centered horizontally. In addition to center, you can also use the right, left, etc. parameters
# Set the horizontal and vertical centering data B1 in the center sheet [ 'B1']. Alignment = Alignment (horizontal = 'center', vertical = 'center')
Row and column width set high
and sometimes too long the data can not be displayed, it is necessary pulled elongated cells.
# 2 trekking high sheet.row_dimensions [2] = 40 .height # column C column width sheet.column_dimensions [ 'C']. Width = 30
Merging and splitting cells
The so-called merge cells, that is, the upper-left cell of the merged area as a reference, so that it covers the other cells known as a large cell.
Instead, this value will split cells large cell returns to the original position of the top left corner.
# Merged cell, to write data to the upper left corner sheet.merge_cells ( 'B1: G1') # combined row few cells sheet.merge_cells ( 'A1: C3') # combined unit of a rectangular region grid
After the merger can only write data to the upper left corner, which is in the range: the coordinates of the left.
If you want to merge these cells have the data, it will only retain the upper left corner of the data, while others are discarded. In other words, if combined before data is not written in the top left corner, no data is merged cell.
The following code is split cells. After the split, the value back to the A1 position.
sheet.unmerge_cells('A1:C3')
The content of excel spreadsheet, mysql import data into the database:
import pymysql from openpyxl import load_workbook db = pymysql.connect('127.0.0.1','root','123','web') cursor = db.cursor() insert_sql = '''insert into student values(%s,%s)''' wd = load_workbook('学生.xlsx') s = wd['学生'] rows = s.max_row columns = s.max_column data=[] for rx in range(1,rows+1): for cx in range(1,columns+1): data.append(str(s.cell(row=rx, column=cx).value)) cursor.execute(insert_sql,(data[0],data[1])) data=[] db.commit()
You may encounter errors when doing the operation table:
1 file in the open state, the operating documents for errors
save_workbook archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True) File "C:\Python36\lib\zipfile.py", line 1113, in __init__ self.fp = io.open(file, filemode) PermissionError: [Errno 13] Permission denied: '城市.xlsx'
Column 2 when reading data, it is necessary to write read_only = False or not default False,
File "G:/python/exel/readfile.py", line 23, in <module> col = wb1.columns AttributeError: 'ReadOnlyWorksheet' object has no attribute 'columns'