安装:
pip install pypiwin32
import win32com.client as win32
#创建
xlApp = win32.Dispatch("Excel.Application")
xlApp = win32.DispatchEx("Excel.Application")#使用启动独立的进程
#后台运行, 不显示, 不警告
xlApp .Visible = 0;
xlApp DisplayAlerts = 0;
#打开新的文件
xlBook = xlApp.Workbooks.Open(FileName)
#创建新的工作簿
new_xlBook = xlApp.Workbooks.Add()
#获取
xlSheet = xlBook.Worksheets('Sheet1')
a = xlSheet .Cell(11, 5).Value # (row, col) 都是从1开始
xlSheet .Cells(11, 5).Value = 2 # (row, col) 都是从1开始
#范围操作
xlSheet.Range(xlSheet.Cell(11, 5), xlSheet.Cell(13, 6)).Value
#添加图片
xlSheet.Shapes.AddPicture(picturename, 1, 1, Left, Top, Width, Height)
#copy 工作簿
xlSheet2.Copy(None, xlSheet)
#保存
xlBook.SaveAs(FileName)#另存为
xlBook.Save()
#退出
xlBook.Close()
xlBook.Quit()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import win32com.client as win32
if __name__ == "__main__":
''' 启动Excel程序并打开文件 '''
app = win32.DispatchEx('Excel.Application') # 启动独立的进程,关闭时不影响其他文件
app.Visible = False # 不打开excel界面
app.DisplayAlerts = False # 不显示警告信息
wb = app.Workbooks.Open(r'D:\6_SoftwareTest\xml\empty_book.xlsx')
# wb = app.Workbooks.Add() #创建新文件
''' 处理worksheet '''
ws = wb.Worksheets('Sheet1')
ws.Cells(11, 5).Value = 2 # Cells(row,col) 先行后列 Cells(11,5)就指的是 E11单元格
ws.Cells(11, 5).offset(3, 2).Value = 1 # E11 偏移后 到了 F13,移动(3-1,2-1)
ws.Range('D10').value = 15 # 这里指对D10写入数据 15
ws1 = wb.Worksheets
ws1.Copy(None, ws)
''' 保存并关闭Excel文件,退出程序 '''
wb.Save()
# wb.SaveAs(path)
wb.Close()
app.Quit()
import win32com.client as win32
#创建
wdApp = win32.Dispatch("Word.Application")
wdApp = win32.DispatchEx("Word.Application")#使用启动独立的进程
#后台运行, 不显示, 不警告
wdApp.Visible = 0;
wdApp.DisplayAlerts = 0;
#打开新的文件
doc = wdApp.Documents.Open(FileName)
#创建新的文档
new_doc = wdApp.Documents.Add()
#插入文字
myRange = doc.Range(0, 0)
myRange.InsertBefore("hello from Python")
#使用样式
wordStyle = myRange.Select()
wordStyle.Style = constants.wdStyleHeading1
#正文文字替换
wdApp.Selection.Find.ClearFormatting()
wdApp.Selection.Find.Replacement.ClearFormatting()
wdApp.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
#表格操作
doc.Tables[0].Rows[0].Cells[0].Range.Text = "hello world Python"
doc.Tables[0].Rows.Add() #增加一行
#转换为html
wc = win32.constants
wdApp.ActiveDocument.WebOptions.RelyOnCSS = 1
wdApp.ActiveDocument.WebOptions.OptimizeForBrowser = 1
wdApp.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
wdApp.ActiveDocument.WebOptions.OrganizeInFolder = 0
wdApp.ActiveDocument.WebOptions.UseLongFileNames = 1
wdApp.ActiveDocument.WebOptions.RelyOnVML = 0
wdApp.ActiveDocument.WebOptions.AllowPNG = 1
wdApp.ActiveDocument.SaveAs(FileName, FileFormat = wc.wdFormatHTML)
#打印
doc.PrintOut()
#保存
doc.SaveAs(FileName)#另存为
doc.Save()
#关闭
doc.Close()
wdApp.Quit()