PYTHON操作EXCEL,实例代码
2010-10-05 10:10
876 查看
用pywin32了。我前段时间刚刚做过这方面的东西,给你一段代码希望对你有所帮助。Python code
from win32com.client import Dispatch import win32com.client 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 = win32com.client.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 GetExcelLineCount(self): count = 0 sht = self.xlBook.Worksheets( ' 第一轮 ' ) while True: if sht.Cells(count + 1 , 1 ).Value == None: break count += 1 return count def getCell(self, sheet, row, col): " Get value of one cell " sht = self.xlBook.Worksheets(sheet) return sht.Cells(row, col).Value def setCell(self, sheet, row, col, value): " set value of one cell " sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Value = value def getRange(self, sheet, row1, col1, row2, col2): " return a 2d array (i.e. tuple of tuples) " sht = self.xlBook.Worksheets(sheet) return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value if __name__ == " __main__ " : xls = easyExcel( ' D:/用户目录/pythonworkspace/excel2doc/src/test.xls ' ) lineNum = xls.GetExcelLineCount() for i in range( 1 ,lineNum + 1 ): for j in range( 1 , 8 ): print i,j,xls.getCell( ' 第一轮 ' , i, j) xls.save() xls.close()
相关文章推荐
- Python对excel写入数据操作实例代码(只供参考)
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- Python对excel写入数据操作实例代码(只供参考)
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- Python对excel写入数据操作实例代码(只供参考)
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- Python对excel写入数据操作实例代码(只供参考)
- python3结合openpyxl库实现excel操作的实例代码
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- C# 通过 oledb 操作Excel实例代码
- python中使用xlrd读excel使用xlwt写excel的实例代码
- python中string的相关操作实例代码
- Python修改Excel数据的实例代码
- Python操作使用MySQL数据库的实例代码
- Python操作Mysql实例代码
- Python处理Excel文件实例代码
- Python操作Mysql实例代码教程
- 【python】解析Excel中使用xlrd库、xlwt库操作,读取excel进阶完整脚本实例(四)
- 关于python 自带csv库的使用心得 附带操作实例以及excel下乱码的解决