Python 针对Excel操作

1.python 读取Excel

# -*- coding: utf-8 -*-
import xlrd
import os,sys

reload(sys)
sys.setdefaultencoding("utf8")

filename = 'text.xlsx'
filename = filename.decode('utf-8')
book = xlrd.open_workbook(filename)
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
print u'表格总行数 ',nrows
ncols = sheet1.ncols
print u'表格总列数 ',ncols


##查询表头
excelhead = []
for i in range(ncols):
  excel_head_values = sheet1.col_values(i)
  excelhead.append(excel_head_values[0])


##查询行的值
excelhang = []
for i in range(nrows)[1:]:
  row_values = sheet1.row_values(i)
  print 'User:' + row_values[2] + ' Filename:' + row_values[0] + ' Tablename:' + row_values[1]

text.xlsx内容如下:

运行结果:

表格总行数  4
表格总列数  3
User:edw Filename:sh002_zyb_tx_chk_h0200.py Tablename:SH002_ZYB_TX_CHK_H0200
User:etl Filename:sh002_a_h0200.py Tablename:SH002_A_H0200
User:app Filename:sh002_b_h0200.py Tablename:SH002_B_H0200

 

2.python 写入Excel

# -*- coding: utf-8 -*-
import xlwt
import pymysql

def sql_connect(sql):
    conn = pymysql.connect(host='192.168.3.xx',port=3306, user='root', password='123456',db='hive',charset='utf8')
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    return data


def write_excel(filename, data):
    book = xlwt.Workbook()            #创建excel对象
    sheet = book.add_sheet('PARTITIONS')  #添加一个表Sheet
    c = 0  #保存当前列
    for d in data: #取出data中的每一个元组存到表格的每一行
        for index in range(len(d)):   #将每一个元组中的每一个单元存到每一列
            sheet.write(c,index,d[index])
        c += 1
    book.save(filename) #保存excel


sql = 'select *  from PARTITIONS limit 100'
res = sql_connect(sql)
write_excel('partitions.xls', res)

 

运行结果:

-rw-r--r-- 1 root root 17920 8月   6 11:53 partitions.xls

 

 

3.python Excel写入表内

# -*- coding: utf-8 -*-
import xlwt
import xlrd
import pymysql

#从excel读取数据写入mysql
def excel_to_mysql(filename):
    conn = pymysql.connect(host='192.168.3.xx',port=3306, user='root', password='123456',db='hive',charset='utf8')
    cur = conn.cursor()     #连接数据库
    book = xlrd.open_workbook(filename)
    sheet = book.sheet_by_name('Sheet1')
    rows = sheet.nrows      #获取行数
    for r in range(1,rows): #将标题之外的其他行写入数据库
        r_values = sheet.row_values(r)
        sql = 'insert into user_zw values(%s,%s,%s)' #有几个字段需要几个%s
        data = cur.execute(sql,r_values)  #将每一行插入sql
    conn.commit()           #插入所有数据后提交
    cur.close()
    conn.close()

excel_to_mysql('user_zw.xls')

 

 user_zw.xls的内容:

 

查询表中内容:

 

posted @ 2019-08-06 15:07  醉城、  阅读(1417)  评论(0编辑  收藏  举报