安装环境
Python Extensions for Windows (http://pywin32.sf.net)
模块安装
pip install xlrd
pip install xlwt
Excel操作
Excel代码1
#-*- coding: utf-8 -*-
import pandas as pd
#参数初始化
inputfile= 'tmp/in.xls' #原始数据文件
outputfile = 'tmp/out.xls' #输出数据文件
data = pd.read_excel(inputfile) #读入数据
data[u'线损率'] = (data[u'供入电量'] - data[u'供出电量'])/data[u'供入电量'] # 计算并写入新的数据
data.to_excel(outputfile, index = False) #保存结果
Excel代码2
#-*- coding: utf-8 -*-
import xlrd
import xlwt
rfile = xlrd.open_workbook("tmp/qq88191924.xls")
rsheet = rfile.sheet_by_name(u'好友信息')
wfile = xlwt.Workbook()
wsheet = wfile.add_sheet(u'qq好友表',cell_overwrite_ok = True)
rncols = rsheet.ncols
rnrows = rsheet.nrows
print rncols
print rnrows
wsheet.col(1).width = 3333 # 3333 = 1" (one inch). #设置列宽
alignment = xlwt.Alignment() # Create Alignment
style = xlwt.XFStyle() # Create Style
style.alignment = alignment
wsheet.write(0,0,u'用户账号')
wsheet.write(0,1,u'QQ好友',style)
for i in range(1,rnrows):
tmp = rsheet.cell(i,1).value
tmp = int(tmp)
print tmp
wsheet.write(i,0, 88191924)
wsheet.write(i,1, tmp,style)
wfile.save(u"tmp/QQ好友总表.xls")
Excel代码3
from Tkinter import Tk
from time import sleep
from tkMessageBox import showwarning
import win32com.client as win32
# 弹出警告框,显示“Exit?”
warn = lambda app: showwarning(app,'Exit?')
RANGE = range(3,8)
def excel():
app = 'Excel'
# 创建 Excel 文件
x1 = win32.gencache.EnsureDispatch('%s.Application' % app)
# 创建Excel的Workbooks
ss = x1.Workbooks.Add()
# 指向当前活动的sheet表
sh = ss.ActiveSheet
# Excel程序可见,使得可见下面程序对Excel操作的自动执行。
x1.Visible = True
# 该程序操作延时一秒
sleep(1)
# 单元格赋值, 字符变量:“%s”,变量名: “app”, 标识符:“%”。
sh.Cells(1,1).Value = 'Python-to-%s Demo' % app
sleep(1)
for i in RANGE:
# 单元格赋值, 整数变量:“%d”,变量名:“i”,标识符:“%”。
sh.Cells(i,1).Value = 'LIne %d' % i
sleep(1)
sh.Cells(i+2,1).Value = "Th-th-th-that's all folks!"
# 将Excel程序窗口句柄传递给warn函数
warn(app)
# 关闭当前Workbooks,保存(True),不保存(False)
ss.Close(False)
# 关闭Excel程序
x1.Application.Quit()
if __name__ == '__main__':
Tk().withdraw()
excel()