手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

Python操作word和excel

时间:2024-10-12 20:22:20

1、载入模块xlrd,打开工作表open_workbook()import xlrdpath='C:\\Users\\jyj茑霁酌绡h\\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

Python操作word和excel
Python操作word和excel

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)

Python操作word和excel

3、对新建的word文档进行操作,包括设置字体形式,import win32com.clientwordapp=win32com.cl足毂忍珩ient.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')保存文档

Python操作word和excel
Python操作word和excel

4、通过两者的结合将Excel中的数据写入到Word中。import xlrdpath='C:\\Users\\jyjh\\Desktop\\data.xlsx'data=xlrd.open_workbook(path)sheet1=data.sheet_by_index(0)row1=sheet1.row_values(1)import win32com.clientwordapp=win32com.client.Dispatch("Word.Application")#create a new blank documentdocx=wordapp.Documents.Add()select=wordapp.Selectionselect.Font.Name="黑体"select.Font.Size=12select.Font.Bold=Trueselect.TypeText(row1)docx.SaveAs('C:\\Users\\jyjh\\Desktop\\demo.docx')

Python操作word和excel
© 手抄报圈