python操作excel

python操作excel表格是怎样的呢?下面就让我们一起来了解一下吧:

python操作excel一般是会用到xlrd与xlwt这两个库,也就是xlrd为读取excel,xlwt则是写excel的库。

不过需要先安装好xlrd模块,可以直接到到python官网下载,当然前提是已经安装了python环境。

此外,在单元格中的常用数据类型有0.empty(空的),1string(text),2number,3date,4boolean,5error,6blank(空白表格)。

参考范例:

运用xlwt写excel,具体指令为:

import xlwt

#设置表格样式

def set_style(name,height,bold=False):

style = xlwt.XFStyle()

font = xlwt.Font()

font.name = name

font.bold = bold

font.color_index = 4

font.height = height

style.font = font

return style

#写Excel

def write_excel():

f = xlwt.Workbook()

sheet1 = f.add_sheet('学生',cell_overwrite_ok=True)

row0 = ["姓名","年龄","出生日期","爱好"]

colum0 = ["张三","李四","恋习Python","小明","小红","无名"]

#写第一行

for i in range(0,len(row0)):

sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))

#写第一列

for i in range(0,len(colum0)):

sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True))

sheet1.write(1,3,'2006/12/12')

sheet1.write_merge(6,6,1,3,'未知')#合并行单元格

sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格

sheet1.write_merge(4,5,3,3,'打篮球')

f.save('test.xls')

if __name__ == '__main__':

write_excel()

运用xlrd读excel,一般需要先打开文件,选定表格,然后读取行列内容,再读取表格内数据,具体指令为:

import xlrd

from datetime import date,datetime

file = 'test3.xlsx'

def read_excel():

wb = xlrd.open_workbook(filename=file)#打开文件

print(wb.sheet_names())#获取所有表格名字

sheet1 = wb.sheet_by_index(0)#通过索引获取表格

sheet2 = wb.sheet_by_name('年级')#通过名字获取表格

print(sheet1,sheet2)

print(sheet1.name,sheet1.nrows,sheet1.ncols)

rows = sheet1.row_values(2)#获取行内容

cols = sheet1.col_values(3)#获取列内容

print(rows)

print(cols)

print(sheet1.cell(1,0).value)#获取表格里的内容,三种方式

print(sheet1.cell_value(1,0))

print(sheet1.row(1)[0].value)

标签:excel python

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
  • excel随内容改变自动排序
    excel随内容改变自动排序
    08-05
  • excel如何使用合并计算
    excel如何使用合并计算
    08-05
  • python 字符串连接
    python 字符串连接
    08-05
  • excel不规则隔行求和
    excel不规则隔行求和
    08-05
  • excel表格在哪里插入剪贴画
    excel表格在哪里插入剪贴画
    08-05
  • Python工程师待遇如何
    Python工程师待遇如何
    08-05
  • python str函数
    python str函数
    08-05
  • excel对角线怎么画
    excel对角线怎么画
    08-05
  • python中str是什么意思
    python中str是什么意思
    08-05
  • excel处于锁定状态怎么解除
    excel处于锁定状态怎么解除
    08-05