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')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章