python openpyxl module for reading excel, and create a new table and append new data to the original data table

When work needs to excel table data read out, or some statistical data is written excel table, a design-rich, easy to find documentation of the module will be particularly attractive, this common module for openpyxl usage do some recording, to facilitate the work of the inquiry (a good memory as bad written)

    author: of He
    QQ: 760 863 706
    Python: 3.5
    DATE: 2018-9-14

1: installation openpyxl

PIP install openpyxl

    1

2: Excel data table read (.xlsx )

Import openpyxl
filepath = 'sample.xlsx'
WB = openpyxl.load_workbook (filepath)
# obtain all table
sheetnames = wb.sheetnames
# handover to the target data table
#ws WB = []
WS WB = [ 'Sheet2']
# table number of rows
MAX_ROW = ws.max_row
# the total number of columns in the table
max_col = ws.max_column
for x in Range (. 1, MAX_ROW):
    # Get row in table 1 x values
    cell_data = ws.cell (row = x, column = 1 ) .Value

    1
    2
    . 3
    . 4
    . 5
    . 6
    . 7
    . 8
    . 9
    10
    . 11
    12 is
    13 is
    14
    15

. 3: Append the data table already exists Excel

Import openpyxl
filepath = 'sample.xlsx'
WB = openpyxl.load_workbook (filepath)
# switch to the target data table
#ws = wb [ ]
WS WB = [ 'Sheet2']
# to be filled data
data = [[l, 2,3], [4,5,6]]
for X in data:
    ws.append (X)
SAVENAME = 'update_excel.xlsx'
wb.save (SAVENAME)

    . 1
    2
    . 3
    . 4
    . 5
    . 6
    . 7
    . 8
    . 9
    10
    11
    12

4: Create a new excel table

Import openpyxl
filepath = 'new_excel.xlsx'
wb = openpyxl.Workbook ()
# default table sheet1
ws1 = wb.active
# Change the name of the table
ws1.title = 'new_sheet_name'
# Create a table sheet2
ws2 = wb.create_sheet ( 'Sheet2')
ws1.cell (row =. 1, column =, value = 'value of a row of table 1 sheet1'. 1) .Value
ws2.cell (row = 2, column = 2, value = ' sheet2 table value 2 of 2 rows') .Value
wb.save
(filepath) ----------------
Disclaimer: This article is the original article CSDN bloggers "weixin_38336920", following CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/weixin_38336920/article/details/82703209

Guess you like

Origin www.cnblogs.com/graybird/p/11517379.html