python写excel总结

废话不说,直接上代码:
import xlrd
import xlwt
# 读excel然后写到mysql的套路
def updata_info():
book = xlrd.open_workbook("tb_yuzhao.xls")
sheet = book.sheet_by_name("sheet1")

# 建立数据库连接
db = MySQLdb.connect(。。。。。。。)
# 游标对象,用于数据库逐行遍历
cursor = db.cursor()

# 创建一个for循环迭代读取xls文件每行数据的, 从第二行开始是要跳过标题
for r in range(1, sheet.nrows):
code_name = sheet.cell(r, 0).value
multi_desc = sheet.cell(r, 3).value
# 执行sql语句
update_sql = 'update yuzhao set desc = "{0}" where code_name = "{1}"'.format(desc, code_name)
print update_sql
cursor.execute(update_sql)
cursor.close()
db.commit()
db.close()
print 'Done!'

# 写excel的套路
def write_excel(filename, data):
book = xlwt.Workbook() # 创建excel对象
sheet = book.add_sheet('sheet1') # 添加一个表
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

猜你喜欢

转载自www.cnblogs.com/yuzhaoblog/p/9055654.html