- 论坛徽章:
- 0
|
- from win32com.client import Dispatch
- class easyExcel:
- """A utility to make it easier to get at Excel. Remembering
- to save the data is your problem, as is error handling.
- Operates on one workbook at a time."""
- def __init__(self, filename=None):
- self.xlApp = Dispatch('Excel.Application')
- if filename:
- self.filename = filename
- self.xlBook = self.xlApp.Workbooks.Open(filename)
- else:
- self.xlBook = self.xlApp.Workbooks.Add()
- self.filename = ''
- def save(self, newfilename=None):
- if newfilename:
- self.filename = newfilename
- self.xlBook.SaveAs(newfilename)
- else:
- self.xlBook.Save()
- def close(self):
- self.xlBook.Close(SaveChanges=0)
- del self.xlApp
-
- def getCell(self, sheet, row, col):
- "Get value of one cell"
- sht = self.xlBook.Worksheets(sheet)
- return sht.Cells(row, col).Value
-
- def getContiguousRange(self, sheet, row, col):
- """Tracks down and across from top left cell until it
- encounters blank cells; returns the non-blank range.
- Looks at first row and column; blanks at bottom or right
- are OK and return None within the array"""
- sht = self.xlBook.Worksheets(sheet)
- # find the bottom row
- bottom = row
- while sht.Cells(bottom + 1, col).Value not in [None, '']:
- bottom = bottom + 1
- # right column
- right = col
- while sht.Cells(row, right + 1).Value not in [None, '']:
- right = right + 1
- return sht.Range(sht.Cells(row, col), sht.Cells(bottom, right)).Value
- if __name__ == '__main__':
- filename = r'list.xls'
- sheet = r'sheet1'
- staff = easyExcel(filename)
- ## print staff.getContiguousRange(sheet, 1,1)
- print staff.getCell(sheet, 1,1)
- staff.close()
复制代码 |
|