免费注册 查看新帖 |

Chinaunix

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

请教一下用python操作excel的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-23 09:37 |只看该作者 |倒序浏览
from win32com.client import Dispatch
xls=Dispatch('Excel.Application')
xls.Visible=1
xls.Workbooks.Add()
for i in range(1,10,1):
  for j in range(1,10,1):
    xls.Cells(i,j).Value=i*j
wb.SaveAs(Filename='e:\\b.xls')


如上,默认是将数据写入'Sheet1',怎样建立一个名称为'test'的工作表,然后将数据写入到这个工作表里面呢?
在网上找了好久都没发现解决方法,只好到这里请教大家了.

[ 本帖最后由 kaminjo 于 2009-11-23 09:38 编辑 ]

论坛徽章:
1
技术图书徽章
日期:2014-03-06 15:29:50
2 [报告]
发表于 2009-11-23 13:56 |只看该作者
应该是add里面加参数吧,没用过这个模块,我用的pyExcelerator,add里面可以加数据表的参数

论坛徽章:
0
3 [报告]
发表于 2009-11-24 09:50 |只看该作者
找到方法了

论坛徽章:
0
4 [报告]
发表于 2009-11-24 16:48 |只看该作者
分享一下哈!

论坛徽章:
0
5 [报告]
发表于 2009-11-24 17:11 |只看该作者
原来楼上也需要么

#!/usr/bin/env python

from win32com.client import Dispatch

xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1

# Check if any workbook exists.
if xlApp.Workbooks.Count == 0:
    # If not, create a new one.
    workbook = xlApp.Workbooks.Add()
else:
    # If yes, use the first one.
    workbook = xlApp.Workbooks[0]

# Check if any sheet exists.
if workbook.Sheets.Count == 0:
    # If not, add a sheet to current workbook.
    sheet = workbook.Sheets.Add()
else:
    # If yes, use the first sheet of current workbook.
    sheet = workbook.Sheets[0]
    
# Generate the multiplication table(9x9).
for i in xrange(2, 10):
&nbsp;&nbsp;&nbsp;&nbsp;# Cells(<column>, <row>)
&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(1, i).Value = i
&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(1, i).Font.Color = 0xFF0000
&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(i, 1).Value = i
&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(i, 1).Font.Color = 0x00FF00
&nbsp;&nbsp;&nbsp;&nbsp;
def a2i(ch):
&nbsp;&nbsp;&nbsp;&nbsp;return ord(ch.upper()) - ord('A') + 1

def i2a(i):
&nbsp;&nbsp;&nbsp;&nbsp;return chr((i-1) + ord('A'))
&nbsp;&nbsp;&nbsp;&nbsp;
for i in xrange(2, 10):
&nbsp;&nbsp;&nbsp;&nbsp;for j in xrange(2, 10):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Generate the Excel formula.      
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(i, j).Formula = '=%s1*A%s' % (i2a(j), i)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sheet.Cells(i, j).Font.Color = 0x000000
sheet.Name = "Multiplication Table"
workbook.SaveAs('xxx.xls')
xlApp.Quit()
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP