记录使用 xlrd/xlwt/xlutils 模块操作excel 文件的方法
1. sqlite3 db 数据库文件中的数据写入到 excel 中
import sys
import os
import xlrd
import xlwt
from xlutils.copy import copy
import time
import checkservice
from configmanage import ConfigManage
from db_operate import DBOperate
class ExportService(object):
def __init__(self):
#TODO
pass
def _create_output_excel_path(self):
"""
创建输出的excel 结果文件的路径
:return:
"""
# 生成输出文件路径
output_path = self._cm.get_option_value('io_info', 'output_path')
if not os.path.exists(output_path):
os.makedirs(output_path)
# export_data_202002220948.xls
output_file_name = 'export_data' + '_' + time.strftime('%Y%m%d%H%M', time.localtime(time.time())) + '.xls'
output_file_path = os.path.join(output_path, output_file_name)
# print output_file_path
return output_file_path
def _write_result_to_excel(self, key, search_key_value_dict, output_file_path):
"""
数据库查询结果写到excel 文件中
:param key: 查询的业务图表名称
:param search_key_value_dict: {'date_list':[],'field': ['field1','field2'], 'query_result': [[(value1, value2,...)], [(value1, value2,...)],...]}
:param output_file_path: 输出文件路径
:return:
"""
if os.path.exists(output_file_path):
# TODO 打开已经存在的excel 文件, xlrd.Book formatting_info=True 表示读取原文件的格式
temp_result_workbook = xlrd.open_workbook(output_file_path, formatting_info=True)
# TODO 利用xlutils.copy函数,将xlrd.Book转为xlwt.Workbook,再用xlwt模块进行存储
result_workbook = copy(temp_result_workbook)
else:
# TODO 文件不存在
# 创建一个新的文件 encoding='utf-8'
result_workbook = xlwt.Workbook(encoding='utf-8')
# 新增一个sheet, sheet 名字为 对应的业务图表名称
# print type(key)
new_sheet = result_workbook.add_sheet(key.decode('utf-8'))
field_list = search_key_value_dict.get('field')
query_value_list = search_key_value_dict.get('query_result')
date_list = search_key_value_dict.get('date_list')
# 列数
columns_len = len(field_list)
# 行的索引
row_index = 0
# 控制表头
table_head_flag = True
for index, query_value in enumerate(query_value_list):
# query_value 格式 [(1,2,3)]
if table_head_flag:
# 先写日期
new_sheet.write(row_index, 0, date_list[index])
row_index += 1
# 再写表头
for column_index in range(0, columns_len):
# print type(field_list[column_index])
# TODO 表头字段 字符串类型转换为 unicode !!!!
new_sheet.write(row_index, column_index, field_list[column_index].decode('utf-8'))
# TODO 设置宽度 256为衡量单位,20表示20个字符宽度
new_sheet.col(column_index).width = 256 * 20
row_index += 1
table_head_flag = False
# 写结果内容
for every_value in query_value:
for column_index in range(0, columns_len):
single_every_value = every_value[column_index]
#if isinstance(single_every_value, unicode):
# single_every_value = single_every_value.decode('unicode_escape')
# print type(single_every_value)
# print type(single_every_value)
new_sheet.write(row_index, column_index, single_every_value)
row_index += 1
# 每写完一个日期的查询内容后空两行
row_index += 2
table_head_flag = True
# 查询结果写sheet
result_workbook.save(output_file_path)
参考链接:
https://www.cnblogs.com/jiangzhaowei/p/6179759.html
https://www.cnblogs.com/jingshuhui/p/9801340.html