多语言展示
当前在线:780今日阅读:176今日分享:34

Python操作word和excel

win32com是用于处理MS软件的python模块,对于需要批量处理word或者excel文件的用户来说,是一个不错的选择,当然MS本身提供VBA,两者可以互为补充。
工具/原料
1

python3.4

2

win32com

方法/步骤
1

载入模块xlrd,打开工作表open_workbook()import xlrdpath='C:\\Users\\jyjh\\Desktop\\data.xlsx'#open the workbookdata=xlrd.open_workbook(path)#get the data from the sheet#select the sheet by indexsheet1=data.sheet_by_index(0)#select the sheet by list indexsheet1=data.sheets()[0]#select the sheet by namesheet1=data.sheet_by_name(u'Sheet1')#get the sheet row valuesrow1=sheet1.row_values(1)#get the column valuescolumn1=sheet1.col_values(1)#get the sheet number of rowsnumber_of_rows=sheet1.nrows#get the number of columnsnumber_of_columns=sheet1.ncols#traverse the sheet by rowsfor i in range(number_of_rows):    print(sheet1.row_values(i))#get the cell valuecell_A1=sheet1.cell(0,0).valuecell_A2=sheet1.cell(1,0).valuecell_A1=sheet1.row(0)[0].valuecell_A2=sheet1.col(1)[0].value#the simple write valuerow=0col=0#type empty:0;string:1;number:2;date:3;boolean:4;error:5celltype=1value='数值'xf=0sheet1.put_cell(row,col,celltype,value,xf)sheet1.cell(0,0)sheet1.cell(0,0).value

2

新建一个word文档或者打开一个已存在word文档import win32com.clientwordapp=win32com.client.Dispatch('Word.Application')#create a new blank documentdocx=wordapp.Documents.Add()#open an exit documentdocx=wordapp.Documents.Open(filepath)

3

对新建的word文档进行操作,包括设置字体形式,import win32com.clientwordapp=win32com.client.Dispatch('Word.Application')#create a new blank documentdocx=wordapp.Documents.Add()select=wordapp.Selection#select the font style#font name='黑体','宋体'select.Font.Name='黑体'#font size='大一号','五号'select.Font.Size=24#bold,italic,underlineselect.Font.Underline=Trueselect.Font.Italic=True#alignment 0:left 1:center 2:rightselect.ParagraphFormat.Alignment=0#type somethingselect.TypeText('To: whom')select.TypeText('\n')select.Font.Name='宋体'select.Font.Size=15select.Font.Italic=Trueselect.Font.Underline=Falseselect.ParagraphFormat.Alignment=2select.TypeText('From: whom')select.TypeText('\n')#create a tabletable=docx.Tables.Add(select.Range,4,3)table.Style='网格型'table.Rows.Alignment=1table.Cell(1,1).Range.Text='Table1:'for i in range(2,5):    table.Cell(i,1).Range.Text='row'+str(i)for i in range(2,4):    table.Cell(1,i).Range.Text='column'+str(i)#docx.Save(path):save filedocx.SaveAs('C:\\Users\\jyjh\\Desktop\\demo1.docx')保存文档

注意事项

熟悉操作两个模块xlrd和win32com

推荐信息