免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6096 | 回复: 5
打印 上一主题 下一主题

python能对EXCEL文件操作吗? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-06-13 14:35 |只看该作者 |倒序浏览
如:我有一个EXCEL文件,这个EXCEL文件里有SHEET1,SHEET2.我只想对SHEET1操作,SHEET2保势不变.请问用PYTHON如何操作??

论坛徽章:
0
2 [报告]
发表于 2007-06-13 21:58 |只看该作者
  1. from win32com.client import Dispatch

  2. class easyExcel:
  3.     """A utility to make it easier to get at Excel. Remembering
  4.     to save the data is your problem, as is error handling.
  5.     Operates on one workbook at a time."""

  6.     def __init__(self, filename=None):
  7.         self.xlApp = Dispatch('Excel.Application')
  8.         if filename:
  9.             self.filename = filename
  10.             self.xlBook = self.xlApp.Workbooks.Open(filename)
  11.         else:
  12.             self.xlBook = self.xlApp.Workbooks.Add()
  13.             self.filename = ''

  14.     def save(self, newfilename=None):
  15.         if newfilename:
  16.             self.filename = newfilename
  17.             self.xlBook.SaveAs(newfilename)
  18.         else:
  19.             self.xlBook.Save()

  20.     def close(self):
  21.         self.xlBook.Close(SaveChanges=0)
  22.         del self.xlApp
  23.         
  24.     def getCell(self, sheet, row, col):
  25.         "Get value of one cell"
  26.         sht = self.xlBook.Worksheets(sheet)
  27.         return sht.Cells(row, col).Value
  28.    
  29.     def getContiguousRange(self, sheet, row, col):
  30.         """Tracks down and across from top left cell until it
  31.         encounters blank cells; returns the non-blank range.
  32.         Looks at first row and column; blanks at bottom or right
  33.         are OK and return None within the array"""

  34.         sht = self.xlBook.Worksheets(sheet)

  35.         # find the bottom row
  36.         bottom = row
  37.         while sht.Cells(bottom + 1, col).Value not in [None, '']:
  38.             bottom = bottom + 1

  39.         # right column
  40.         right = col
  41.         while sht.Cells(row, right + 1).Value not in [None, '']:
  42.             right = right + 1

  43.         return sht.Range(sht.Cells(row, col), sht.Cells(bottom, right)).Value

  44. if __name__ == '__main__':
  45.     filename = r'list.xls'
  46.     sheet = r'sheet1'
  47.     staff = easyExcel(filename)
  48. ##    print staff.getContiguousRange(sheet, 1,1)
  49.     print staff.getCell(sheet, 1,1)
  50.     staff.close()
复制代码

论坛徽章:
0
3 [报告]
发表于 2007-06-14 08:38 |只看该作者
xlrd, pyexcelerator

分别看一下。

论坛徽章:
0
4 [报告]
发表于 2007-10-24 16:05 |只看该作者
对我很有帮助

论坛徽章:
0
5 [报告]
发表于 2008-01-17 18:11 |只看该作者
调用win32com模块.

论坛徽章:
0
6 [报告]
发表于 2008-01-18 09:06 |只看该作者
学习了~~
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP