Вот несколько методов, которые вы можете использовать с примерами кода для выполнения различных задач, связанных с Microsoft Office 2013:
-
Откройте приложение Office 2013:
import win32com.client as win32 # Open Microsoft Word word_app = win32.gencache.EnsureDispatch('Word.Application') word_app.Visible = True # Open Microsoft Excel excel_app = win32.gencache.EnsureDispatch('Excel.Application') excel_app.Visible = True
-
Создайте новый документ Word и сохраните его:
import win32com.client as win32 word_app = win32.gencache.EnsureDispatch('Word.Application') word_app.Visible = True # Create a new document doc = word_app.Documents.Add() # Add content to the document doc.Content.Text = 'Hello, World!' # Save the document doc.SaveAs('C:\\path\\to\\new_document.docx')
-
Чтение данных из книги Excel:
import win32com.client as win32 excel_app = win32.gencache.EnsureDispatch('Excel.Application') excel_app.Visible = True # Open an existing workbook workbook = excel_app.Workbooks.Open('C:\\path\\to\\workbook.xlsx') # Access a specific worksheet worksheet = workbook.Worksheets('Sheet1') # Read data from a cell cell_value = worksheet.Range('A1').Value # Print the cell value print(cell_value) # Close the workbook workbook.Close()
-
Создайте презентацию PowerPoint и добавьте слайды:
import win32com.client as win32 ppt_app = win32.gencache.EnsureDispatch('PowerPoint.Application') ppt_app.Visible = True # Create a new presentation presentation = ppt_app.Presentations.Add() # Add a slide with a title and content slide = presentation.Slides.Add(1, 1) # 1: Title and content layout slide.Shapes.Title.TextFrame.TextRange.Text = 'Slide Title' slide.Shapes.Placeholders[2].TextFrame.TextRange.Text = 'Slide Content' # Save the presentation presentation.SaveAs('C:\\path\\to\\new_presentation.pptx')
-
Отправить электронное письмо с помощью Outlook:
import win32com.client as win32 outlook_app = win32.Dispatch('Outlook.Application') # Create a new mail item mail_item = outlook_app.CreateItem(0) # 0: Mail item # Set the email properties mail_item.Subject = 'Hello' mail_item.Body = 'This is the body of the email.' mail_item.To = 'recipient@example.com' # Send the email mail_item.Send()