Python3 calls com to read and write Excel files

Source: Internet
Author: User

1. Download and install pywin with version 3.1. Http://sourceforge.net/projects/pywin32/

2. Restart required. Otherwise, the Win32 database cannot be found.

3. Post the Code. For details about the attributes and methods, see the Excel help document.

#! /Usr/bin/ENV Python

From win32com. Client import dispatch
Import win32com. Client
Import WIN32API
Import OS

Class Excel:
Def _ init _ (self, filename = none ):
Self. xlapp = win32com. Client. Dispatch ('excel. application ')
If filename:
Self. filename = filename
If OS. Path. exists (self. filename ):
Self. xlbook = self. xlapp. workbooks. Open (filename)
Else:
Self. xlbook = self. xlapp. workbooks. Add ()
Else:
Self. xlbook = self. xlapp. workbooks. Add ()
Self. filename = 'untitle'

Def save (self, newfilename = none ):
If newfilename:
Self. filename = newfilename
Self. xlbook. saveas (self. filename)

Def close (Self ):
Self. xlbook. Close (savechanges = 0)
Del self. xlapp

Def copysheet (self, before ):
"Copy sheet"
Shts = self. xlbook. worksheets
Shts (1). Copy (none, shts (1 ))

Def newsheet (self, newsheetname ):
Sheet = self. xlbook. worksheets. Add ()
Sheet. Name = newsheetname
Sheet. Activate ()

Def activatesheet (self, sheetname ):
Self. xlbook. worksheets (sheetname). Activate ()

Def activesheet (Self ):
Return self. xlapp. activesheet;

Def getcell (self, row, Col, Sheet = none ):
"Get value of one cell"
If sheet:
Sht = self. xlbook. worksheets (sheet)
Else:
Sht = self. xlapp. activesheet
Return sht. cells (row, col). Value

Def setcell (self, row, Col, value, Sheet = 'sheet1 '):
"Set Value of one cell"
If sheet:
Sht = self. xlbook. worksheets (sheet)
Else:
Sht = self. xlapp. activesheet

Sht. cells (row, col). value = Value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.