DayDayUP_Python自学记录[15]_python execl 读写进阶

读取execl文件内容,txt to execl

导入模块

  import xlrd

打开Excel文件读取数据

   data = xlrd.open_workbook('excelFile.xls')

获取一个工作表

获取所有工作表的所有名称

worksheets = data.sheet_names()

获取所有工作表的总数目

sheetNum=len(data.sheets())

通过索引顺序获取1

table = data.sheets()[0] 

通过索引顺序获取2

table = data.sheet_by_index(0)

通过名称获取

table = data.sheet_by_name(u'Sheet1')

获取整行和整列的值(数组)

table.row_values(i)
table.col_values(i)

获取行数和列数

nrows = table.nrows
ncols = table.ncols

循环行列表数据

for i in range(nrows ):
    print table.row_values(i)

单元格数据

cell_A1 = table.cell(0,0).value

cell_C4 = table.cell(2,3).value

使用行列索引

cell_A1 = table.row(0)[0].value

cell_A2 = table.col(1)[0].value

simpledemo

#/usr/bin/python
# -*- coding: utf-8 -*- 
import  os
import xlrd

#打开execl文件
def open_excel(execlFIle):
    try:
        data=xlrd.open_workbook(execlFIle)
        return data
    except Exception as e:
        print ("打开文件错误",e)


#根据索引获取Excel表格中的数据   参数:Excel文件 
def excel_table_byindex(execlFIle):
    print ("根据sheet索引获取数据")
    data = open_excel(execlFIle)
    sheetNum=len(data.sheets()) #sheet数目
    print ("sheetNum:",sheetNum)

    for num in range(sheetNum):
        table = data.sheets()[num]
        nrows = table.nrows #行数
        ncols = table.ncols #列数
        print ("rows:",nrows)
        print ("cols:",ncols)
         #某一行数据 以一行所有值获取方式
        for row in range(nrows):
            rowValues =  table.row_values(row)
            print ("rownum:",row)
            for value in rowValues:
                print (value)
    return 0

#根据名称获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_name:Sheet1名称
def excel_table_byname(execlFIle):
    print ("根据sheet名称获取数据")
    data = open_excel(execlFIle)
    sheetNames = data.sheet_names()
    print ("all sheets name :",sheetNames)
    for name in sheetNames:
        table = data.sheet_by_name(name)
        nrows = table.nrows #行数
        ncols = table.ncols #列数
        print ("rows:",nrows)
        print ("cols:",ncols)
         #某一行数据  按单元格获取
        for row in range(nrows):
            for col in range (ncols):
                print ("row[%d]col[%d]=%s" % (row,col,table.cell(row,col).value))

    return 0            
def main():
    file=os.path.split(os.path.realpath(__file__))[0]+r"\result.xls"    
    excel_table_byindex(file)
    print("--------------------")
    excel_table_byname(file)

if __name__=="__main__":
    main()

txt2excel (复习上次的execl 写入)

来源: 开源项目 show me the code

将txt文件写入到execl中(包括花括号{},方括号[] )

{
    "1":["wang",150,120,100],
    "2":["赵四",90,99,95],
    "3":["heh",60,66,68]
}

src:

#coding=utf-8
import json, xlwt, os
f = open(os.path.split(os.path.realpath(__file__))[0]+"/student.txt")
dict = json.loads(f.read().decode("GBK"))
xls = xlwt.Workbook() 
sheet = xls.add_sheet("student")
for i in range(len(dict.keys())):
    row = i
    col = 0
    sheet.write(row, col, dict.keys()[i])
    for j in (dict[dict.keys()[i]]):
        col+=1
        sheet.write(row, col, j )
xls.save(os.path.split(os.path.realpath(__file__))[0]+"/student.xls")

out:

1   张三  150 120 100
2   李四  90  99  95
3   王五  60  66  68

将txt文件写入到execl中(包括花括号{},不包含方括号[])

{
    "1":"wang",
    "2":"赵四",
    "3":"heh"
}

src

#/usr/bin/python
#coding utf-8
__author__ = 'laihua'
import xlwt
import os
file=os.path.split(os.path.realpath(__file__))[0]+r"\student.txt"
print (file)
with open(file, 'r') as f:
    content = f.read()
dic = eval(content)
print (dic)

outFile = xlwt.Workbook()
table = outFile.add_sheet('Test', cell_overwrite_ok=True)


def add2excel(key, value):
    table.write(int(key) - 1, 0, key)
    table.write(int(key) - 1, 1, str(value))

# dict.items()  返回元组对的列表
print (dic.items())
for key, value in dic.items():
    add2excel(key, value)

outFile.save('result.xls')

将txt文件写入到execl中(包含方括号[])

txt

[
  [1,2,4,5],
  [1,3,3,4],
  [32,4,34,5]
]

src:

#/usr/bin/python
#coding utf-8
__author__ = 'laihua'
import xlwt
import os
file=os.path.split(os.path.realpath(__file__))[0]+r"\student.txt"
print (file)
with open(file, 'r') as f:
  content=f.read()
lists = eval(content)
print (lists)

outFile = xlwt.Workbook()
outTable = outFile.add_sheet('Test', cell_overwrite_ok=True)


def add2excel(list,table):
  for row in range(len(list)):
    for col in range(len(list[row])):
      table.write(row,col,list[row][col])

# dict.items()  返回元组对的列表
add2excel(lists,outTable)

outFile.save('result.xls')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值