Use XLWT + xlrd + xlutils to manipulate Excel tables
#Coding:utf-8ImportXLWT fromXlrdImportOpen_workbook fromXlutils.copyImportCopyImportOSImportsysreload (SYS) sys.setdefaultencoding ('Utf-8')defSave_excel (my_list): Path=os.getcwd () File_path= path + Os.sep +'Grade.xls'Style_bold= XLWT.EASYXF ('Font:color-index Red, bold on') Header_style=Style_bold Workbook= XLWT. Workbook (encoding='Utf-8') Book_sheet= Workbook.add_sheet ('Sheet 1', cell_overwrite_ok=True) I=0 forX, iteminchEnumerate (my_list): Book_sheet.write (i, X, item, Header_style) Workbook.save (file_path)defXlutil (my_list):Try: Path=os.getcwd () File_path= path + Os.sep +'Grade.xls'Rexcel= Open_workbook (File_path, Formatting_info=true)#read an Excel file using the method provided by Wlrdrows = Rexcel.sheets () [0].nrows#use the method provided by WLRD to get the number of rows you have now Print "rows:", Rows First_row= ['title','Pub_time','Aid','View','Danmaku','Favorite','Coin','Share','author','Sex'] Style_bold= XLWT.EASYXF ('Font:color-index Red, bold on') Header_style=style_bold Excel= Copy (Rexcel)#convert XLRD objects to XLWT objects using the Copy method provided by XlutilsTable = Excel.get_sheet (0)#get the sheet you want to manipulate by using the Xlwt object method ifrows = =0: forY, ValueinchEnumerate (First_row): Table.write (rows, y, Value.decode ('Utf-8'), Header_style) Excel.save (file_path)Else: forY, ValueinchEnumerate (my_list): Table.write (rows, y, Value.decode ('Utf-8')) Excel.save (File_path)exceptException, E:PrintePrint "Please close Grade.xls first"if __name__=='__main__': #path = OS.GETCWD () #file_path = path + os.sep + ' Grade.xls ' #w = xlwt. Workbook (encoding= ' utf-8 ') #ws = W.add_sheet (' Sheet 1 ', cell_overwrite_ok=true) #W.save (File_path)My_list = [' the','2017-10-16 14:42',' -',' the','1','3','0','0',' the',' -'] #Save_excel (my_list)Xlutil (My_list)
Python Operations Excel table