欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

3分钟学会Python 针对Excel操作

程序员文章站 2022-03-21 17:06:01
1.python 读取Excel text.xlsx内容如下: 运行结果: 2.python 写入Excel 运行结果: rw r r 1 root root 17920 8月 6 11:53 partitions.xls 3.python Excel写入表内 user_zw.xls的内容: 查询表 ......

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内容如下:

3分钟学会Python 针对Excel操作

运行结果:

表格总行数  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操作

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的内容:
3分钟学会Python 针对Excel操作

查询表中内容:
3分钟学会Python 针对Excel操作