Python study notes - EXCEL operation

Environment Python3

Create EXCEL, overlay creation

#conding=utf-8
import xlwt

def BuildExcel(ExcelName,SheetName,TitleList,DataList):
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(SheetName)
    col=0
    for title in TitleList:
        sheet.write(0,col,title)
        col=col+1
    row=1
    for rows in DataList:
        col=0
        for column in rows:
            sheet.write(row,col,column)
            col=col+1
        row=row+1   
    workbook.save(ExcelName)

ExcelName = " Incomplete Order.xls " 
SheetName = " Order " #Title

TitleList =[ ' ID ' , ' Order number ' , ' Update status ' ]
#Content DataList
=[(1,1000,1),(2,1001,0)] BuildExcel(ExcelName,SheetName,TitleList,DataList)

Read EXCEL content and return a list

#conding=utf-8
import xlrd

""" Define read function """ 
def ReadExcel(ExcelName,SheetName):
    workbook = xlrd.open_workbook(ExcelName)
    sheet = workbook.sheet_by_name(SheetName)
    return sheet

ExcelName="未完成订单.xls"
SheetName="Order"
sheet = ReadExcel(ExcelName,SheetName)
"""逐行输出"""
"""EXCEL行数:sheet.nrows"""
for i in range(1,sheet.nrows):
    """EXCEL第I行,第N列值:sheet.row_values(i)[N-1]"""
    ID=str(int(sheet.row_values(i)[0]))
    OrderNo=str(int(sheet.row_values(i)[1]))
    Status=str(int(sheet.row_values(i)[1]))
    print(ID,OrderNo,Status)

Edit the EXCEL value and change the cell value according to the ChangeList

# conding=utf-8 
import xlrd
 from xlutils.copy import copy
 #Edit EXCEL, ChangeList passes in the line number, column number and value to be changed. 
# row=row-1, col=col-1, ChangeList=[(row,col,"change value")] 
def EditExcel(ExcelName,ChangeList):
    workbook = xlrd.open_workbook(ExcelName)
    workbooknew = copy(workbook)
    sheet = workbooknew.get_sheet(0)
    for rows in ChangeList:     
        sheet.write(rows[0], rows[1], rows[2])
    workbooknew.save(ExcelName)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325079034&siteId=291194637