码迷,mamicode.com
首页 > 其他好文 > 详细

write_excel

时间:2019-09-20 17:16:37      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:utils   nbsp   ===   active   port   elf   保留   exception   auth   

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 14:05:24 2019

@author: Administrator
"""

import os
import traceback
#import openpyxl
import xlrd
import xlwt
from xlutils.copy import copy


# =============================================================================
# # 操作.xlsx格式excel
# # openpyxl
# class OpenpyxlExcel(object):
#     def __init__(self, filename):
#         root = "d:/test/"
#         self.filename = filename
#         self.path = root + self.filename
#         if not os.path.exists(root):
#             os.mkdir(root)
#         if not os.path.exists(self.path):
#             f = open(self.path, "w")
#             f.close()        
#         self.wb = openpyxl.load_workbook(self.path)
#     
#     
#     def openpyxl_read(self):
#         sheet = self.wb.worksheets[0]
#         self.lsh_tuple = sheet.values
#         yield self.lsh_tuple
#     
#     
#     def openpyxl_write(self, data):
#         sheet = self.wb.active
#         # row 和 col的索引从1开始
#         sheet.active_cell(row=1, column=2, value="流水号")
#         sheet.active_cell(row=1, column=3, value="机构全名")
#         sheet.active_cell(row=1, column=4, value="机构编码")
#         for num in range(len(data)):
#             sheet.active_cell(row=num+2, column=2, value=data[11])
#             sheet.active_cell(row=num+2, column=3, value=data[1])
#             sheet.active_cell(row=num+2, column=4, value=data[1])
#         self.wb.save(self.path)
# =============================================================================


# 操作.xls格式excel
# xlrd  xlwt  xlutils.copy
class OprationExcel(object):
    def __init__(self, filename):
        root = "d:/test/"
        self.filename = filename
        self.path = root + self.filename
        if not os.path.exists(root):
            os.mkdir(root)
            print("创建文件夹%s" % root)
        if os.path.exists(self.path):
            os.remove(self.path)
            f = open(self.path, "w")
            f.close()
        elif not os.path.exists(self.path):
            f = open(self.path, "w")
            f.close()
        else:
            raise Exception

    # 读取信息(根据列索引),保存信息到lsh_list
    def excel_read(self, col_index):
        try:
            rt = xlrd.open_workbook(self.path)
            sheet1 = rt.sheet_by_index(0)
            self.lsh_list = []
            for i in sheet1.col_values(col_index)[1:]:
                self.lsh_list.append(str(i))
            print(self.lsh_list)
        except xlrd.biffh.XLRDError:
            print("文件内容为空")
#            exit()
        except:
            traceback.print_exc()

#        yield self.lsh_list
    
    # 写表头
    def excel_write(self):
        wt = xlwt.Workbook()
        sheet1 = wt.add_sheet("Sheet1")
        
        # row 和 col的索引从0开始
        sheet1.write(0, 0, "序号")
        sheet1.write(0, 1, "流水号")
        sheet1.write(0, 2, "机构名称")
        sheet1.write(0, 3, "机构编码")

        wt.save(self.path)
        print("生成表头成功")

    # 追加数据
    def excel_append(self, data, col):
        # formatting_info=True 保留文件原格式
        wt =  xlrd.open_workbook(self.path, formatting_info=True)
        
        # 复制文件进行操作,直接操作原文件会覆盖
        new_wt = copy(wt)
        new_sheet = new_wt.get_sheet(0)
        for num in range(len(data)):
            new_sheet.write(num+1, col, data[num])
        new_wt.save(self.path)
        print("保存数据成功")
        print("查询结果已生成 %s" % self.path)


test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

if __name__ == "__main__":
    try:
#        excel0 = OpenpyxlExcel("test0.xlsx")
#        excel0.openpyxl_read()
#        excel0.openpyxl_write(test_list)
        
        excel1 = OprationExcel("test1.xls")
        excel1.excel_write()
        excel1.excel_append(test_list, 0)
        excel1.excel_read()
#        excel1.excel_write()
#        excel1.excel_append(test_list)
    except:
        traceback.print_exc()

 

write_excel

标签:utils   nbsp   ===   active   port   elf   保留   exception   auth   

原文地址:https://www.cnblogs.com/zwy-blog/p/11557766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!