VB中操作Excel文档

Wsheet.Rows(iX + 2).Interior.Color = RGB(163, 231, 255)

篇一:利用 Python 操作 Excel文档

利用 Python 操作 Excel

在Excel 2010中打开VBA编辑器,请按 Alt + F11 打开; 以下代码在 Excel 2007, Excel 2010中测试通过;

import win32com.client

# 导入脚本模块

ExcelApp = win32com.client.Dispatch("Excel.Application") # 载入EXCEL模块 ExcelApp.Visible = True

1、新建xls文件

wBook = ExcelApp.Workbooks.Add() 立3个空表

nSheet = wBook.Worksheets.Count wSheet = wBook.Worksheets(1)

# 获取文件的表格数,缺省为3 # 打开指定工作表(注意序号从1开始) # 增加新表,新表为第4个表,相当与

# 新建空文件,每个文件系统默认建

# 显示EXCEL应用程序

wSheet = wBook.Worksheets.Add() wBook.Worksheets(4) wSheet.Name = "新建表格"

# 修改新建表格名称,

或者wBook.Worksheets(4).Name = "新建表格" ……中间操作…… wBook.SaveAs(strName) wBook.Save() wBook.Close()

2、打开和关闭xls文件

xlsPathName = r"E:\000.xls"

# 另存文件,注意直接保存用:

# 关闭文件(账本)

# 指定路径名

# 打开指定文件(账本)

wBook = ExcelApp.Workbooks.Open(xlsPathName) wSheet = wBook.Worksheets(1)

# 打开指定工作表(注意序号从1开始)

# 必须使用准确的工作表名称字

或者wSheet = wBook.Worksheets("Sheet1") 符串

……中间操作…… wBook.Close()

# 关闭文件(账本)

3、页面设置

wSheet.PageSetup.PaperSize = 9

# 设置纸张大小,A3=8,A4=9(与Word不同)

# 设置页面方向,纵向=1,横向=2(与

wSheet.PageSetup.Orientation = 1Word不同)

wSheet.PageSetup.TopMargin = 3*28.35wSheet.PageSetup.BottomMargin = 3*28.35

# 页边距上=3cm,1cm=28.35pt # 页边距下=3cm # 页边距左=2.5cm # 页边距右=2.5cm

wSheet.PageSetup.LeftMargin = 2.5*28.35 wSheet.PageSetup.RightMargin = 2.5*28.35

wSheet.PageSetup.CenterHorizontally = True wSheet.PageSetup.CenterVertically = False后一页不好看)

wSheet.PageSetup.HeaderMargin = 2*28.35 wSheet.PageSetup.FooterMargin = 1*28.35 边)

wSheet.PageSetup.PrintTitleRows = "$1:$2"

# 表格打印位置水平居中

# 表格打印位置垂直不居中(最

# 设置页眉位置=2cm(距上边)

# 设置页脚位置=1cm(距下

# 设置表格标题行

wSheet.PageSetup.CenterHeader = "&\"黑体\"&15表格名称" # 中央页眉作为表格名称 wSheet.PageSetup.CenterFooter = "第&P 页,共&N 页" # 中央页脚显示打印页数

wSheet.Rows(5).PageBreak = -4135

注意:表格名称的文本格式设置,详情查询“页眉和页脚的格式代码”

&"黑体"&15 &B&I&U &L&C&R

4、单元格操作

# 设置字体,字大,颜色

# 在第5行之前插入分页符

# 设置字体加黑、加粗、下划线 # 设置左中右对齐

cv = wSheet.Cells(1, 1).Value # 获取单元格数值

# 设置单元格背景色

wSheet.Cells(1, 1).Interior.Color = 0xff00ff cel = wSheet.Cells(2, 2)

# 获取单元格对象

# 获取偏移后的单元格,即(4,4)

cv = cel.Offset(3, 3).Value

# Offset以当前单元格为(1,1),偏移之后的单元格为(a1+a2-1, b1+b2-1)

注:range与Cells, Rows, Columns的绝大多数属性类似,但是后三者

后面可以接序号(2,3)表示具体单元格或行列,不接序号指所有单元格或行列。

5、行列操作

wSheet.Rows.AutoFit()

# 自动适合行

# 删除第1行

wSheet.Rows(1).Delete()

wSheet.Columns.Autofit() wSheet.Columns(1).Delete()

# 自动适合列

# 删除第1列

# 设置列宽 # 设置数值格式

wSheet.Columns(1).Columnwidth = 30

wSheet.Columns(1).NumberFormatLocal = "000000"

wSheet.Rows("2:2").Select()

# 必须选择第2行,才能冻结第1行!!

# 冻结第1行

ExcelApp.ActiveWindow.FreezePanes = True

6、遍历工作表的所有单元格

nRow = wSheet.usedrange.rows.count

# 获取指定工作表的行数 # 获取指定工作表的列数

nCol = wSheet.usedrange.columns.count for i in range(1, nRow+1): for j in range(1, nCol+1): ……中间操作……break break

# 注意必须分别退出

7、搜索指定数值

cel = wSheet.Columns(2).Find(123) if(cel):

adr = cel.Address while(True): 反复搜索

……中间操作……

cel = wSheet.Columns(2).FindNext(cel) if(cel.Address==adr): break

7、格式设置

wSheet.Cells.Font.Name = "Arial" wSheet.Cells.Font.Size = 10 wSheet.Cells.Font.Bold = True

# 设置字体 # 设置字大 # 设置粗体 # 设置斜体

# 设置所有列自动调整宽度

# 设置左对齐(1=两端, 2=左, 3=

# 注意FindNext()参数为cel

# 获取该单元格首地址,以便退出循环 # 注意系统的FindNext()是个死循环,会

# 在第2列查找某整数值123

# 返回到单元格首地址时,就退出

wSheet.Cells.Font.Italic = True wSheet.usedrange.Columns.AutoFit

wSheet.Cells.HorizontalAlignment = 2 中, 4=右)

ran = wSheet.Range(wSheet.Cells(1,1),wSheet.Cells(nRow,nCol)) ran.Hyperlinks.Delete()ran.Font.Name = "宋体" ran.Font.Size = 10

# 删除指定范围的链接

# 设置字体

# 设置字大 # 设置黑体

# 设置斜体 # 水平对齐 # 垂直对其

ran.Font.Bold = False ran.Font.Italic = True

ran.HorizontalAlignment = -4108 ran.VerticalAlignment = -4108

8、绘制表格线

ran = wSheet.Range("A1:D5")

# 设置处理范围

ran.Borders.LineStyle = 1 条,-4119=双线,-4115虚线)

# 设置线型为实线(1=实线,4=点划线,-4142=无线

ran.Borders(11).LineStyle = -4142 # 去除范围内中间竖线(8=上边线,9=下边线,

7=左框线,10=右框线,11=竖框线,12=横框线)

9、行列宽度设置

wSheet.Rows(1).RowHeight = 20 wSheet.Columns(1).ColumnWidth = 10

10、使用公式进行统计

ran = wSheet.Range("A1:A10")

# 设置计算范围

# 范围数值求和 # 范围最大值

# 设置第1行的行高

# 设置第1列的列宽

a = ExcelApp.WorksheetFunction.Sum(ran) b = ExcelApp.WorksheetFunction.Max(ran)

注:常用函数可以在插入函数对话框中查找,包括 Average, Max, Min, Sum, StDev等;

篇二:python表单提交

#!/usr/bin/python

#-*-coding:utf-8-*-

# 进行表单提交 小项 2008-10-09

import httplib,urllib; #加载模块

#定义需要进行发送的数据

params = urllib.urlencode({'cat_id':'6',

'news_title':'标题-Test39875',

'news_author':'Mobedu',

'news_ahome':'来源',

'tjuser':'carchanging',

'news_keyword':'|',

'news_content':'测试-Content',

'action':'newnew',

'MM_insert':'true'});

#定义一些文件头

headers = {"Content-Type":"application/x-www-form-urlencoded",

"Connection":"Keep-Alive","Referer":"http://192.168.1.212/newsadd.asp?action=newnew"};#与网站构建一个连接

conn = httplib.HTTPConnection("192.168.1.212");

#开始进行数据提交同时也可以使用get进行

conn.request(method="POST",url="/newsadd.asp?action=newnew",body=params,headers=headers);

#返回处理后的数据

response = conn.getresponse();

#判断是否提交成功

if response.status == 302:

print "发布成功!^_^!";

else:

print "发布失败\^0^/";

#关闭连接

conn.close();

篇三:python经典实例

1 输出你好 #打开新窗口,输入:

#! /usr/bin/python

# -*- coding: utf8 -*-

s1=input("Input your name:")

print("你好,%s" % s1)

'''

知识点:

* input("某字符串")函数:显示"某字符串",并等待用户输入.

* print()函数:如何打印.

* 如何应用中文

* 如何用多行注释

'''

2 输出字符串和数字

但有趣的是,在javascript里我们会理想当然的将字符串和数字连接,因为是动态语言嘛.但在Python里有点诡异,如下:

#! /usr/bin/python

a=2

b="test"

c=a+b 运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换 #! /usr/bin/python

#运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换 a=2

b="test"

c=str(a)+b

d="1111"

e=a+int(d)

#How to print multiply values

print ("c is %s,e is %i" % (c,e))

'''

知识点:

* 用int和str函数将字符串和数字进行转换

* 打印以#开头,而不是习惯的//

* 打印多个参数的方式

'''

3 列表 #! /usr/bin/python

# -*- coding: utf8 -*-

#列表类似Javascript的数组,方便易用

#定义元组

word=['a','b','c','d','e','f','g']

#如何通过索引访问元组里的元素

a=word[2]

print ("a is: "+a)

b=word[1:3]

print ("b is: ")

print (b) # index 1 and 2 elements of word.

c=word[:2]

print ("c is: ")

print (c) # index 0 and 1 elements of word.

d=word[0:]

print ("d is: ")

print (d) # All elements of word.

#元组可以合并

e=word[:2]+word[2:]

print ("e is: ")

print (e) # All elements of word.

f=word[-1]

print ("f is: ")

print (f) # The last elements of word.

g=word[-4:-2]

print ("g is: ")

print (g) # index 3 and 4 elements of word.

h=word[-2:]

print ("h is: ")

print (h) # The last two elements.

i=word[:-2]

print ("i is: ")

print (i) # Everything except the last two characters

l=len(word)

print ("Length of word is: "+ str(l))

print ("Adds new element")

word.append('h')

print (word)

#删除元素

del word[0]

print (word)

del word[1:3]

print (word)

'''

知识点:

* 列表长度是动态的,可任意添加删除元素. * 用索引可以很方便访问元素,甚至返回一个子列表

* 更多方法请参考Python的文档

'''

4 字典 #! /usr/bin/python

x={'a':'aaa','b':'bbb','c':12}

print (x[(来自: 小龙 文档 网:python,网页表格)9;a'])

print (x['b'])

print (x['c'])

for key in x:

print ("Key is %s and value is %s" % (key,x[key]))

'''

知识点:

* 将他当Java的Map来用即可.

'''

5 字符串 比起C/C++,Python处理字符串的方式实在太让人感动了.把字符串当列表来用吧. #! /usr/bin/python

word="abcdefg"

a=word[2]

print ("a is: "+a)

b=word[1:3]

print ("b is: "+b) # index 1 and 2 elements of word.

c=word[:2]

print ("c is: "+c) # index 0 and 1 elements of word.

d=word[0:]

print ("d is: "+d) # All elements of word.

e=word[:2]+word[2:]

print ("e is: "+e) # All elements of word.

f=word[-1]

print ("f is: "+f) # The last elements of word.

g=word[-4:-2]

print ("g is: "+g) # index 3 and 4 elements of word.

h=word[-2:]

print ("h is: "+h) # The last two elements.

i=word[:-2]

print ("i is: "+i) # Everything except the last two characters

l=len(word)

print ("Length of word is: "+ str(l)) 中文和英文的字符串长度是否一样?

#! /usr/bin/python

# -*- coding: utf8 -*-

s=input("输入你的中文名,按回车继续");

print ("你的名字是 : " +s)

l=len(s)

print ("你中文名字的长度是:"+str(l))

知识点:

? 类似Java,在python3里所有字符串都是unicode,所以长度一致.

6 条件和循环语句

#! /usr/bin/python

#条件和循环语句

x=int(input("Please enter an integer:"))

if x<0:

x=0

print ("Negative changed to zero")

elif x==0:

print ("Zero")

else:

print ("More")

# Loops List

a = ['cat', 'window', 'defenestrate']

for x in a:

print (x, len(x))

#知识点:

# * 条件和循环语句

# * 如何得到控制台输入

7 函数

#! /usr/bin/python

# -*- coding: utf8 -*-

def sum(a,b):

return a+b

func = sum

r = func(5,6)

print (r)

# 提供默认值

def add(a,b=2):

return a+b

r=add(1)

print (r)

r=add(1,5)

print (r)

一个好用的函数

#! /usr/bin/python

# -*- coding: utf8 -*-

# The range() function

a =range (1,10)

for i in a:

print (i)

a = range(-2,-11,-3) # The 3rd parameter stands for step for i in a:

print (i)

知识点:

? Python 不用{}来控制程序结构,他强迫你用缩进来写程序,使代码清晰. ? 定义函数方便简单

? 方便好用的range函数

8 异常处理

#! /usr/bin/python

s=input("Input your age:")

if s =="":

raise Exception("Input must no be empty.")

try:

i=int(s)

except Exception as err:

print(err)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值