python excel写入及追加写入

# -*- coding:utf-8 _*-
"""
@author:Administrator
@file: excel.py
Description :
如果行数是1000的倍数,进行一次flush,如果行数超过65536,
新开一个sheet,如果超过3个sheet,则新建一个文件
@time: 2018/10/31
"""
import os
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy
from configs.config import ConfigENum

MAX_ROW_NUM = 65536
MAX_SHEET_NUM = 3


class XLS:
def __init__(self, name, captionlist: list, typelist: list, encoding='utf8', flushBound=1000):
"""

:type captionlist: list
:type typelist: list
"""
self.name = name
self.captionlist = captionlist[:]
self.typeList = typelist[:]
self.encoding = encoding
self.flushBound = flushBound
self.bk = xlwt.Workbook(encoding=self.encoding, style_compression=0)
self.workbookIndex = 1
self.row = 0
self.excel_name = None
self.sheet = None
self.sheetindex = 0
# self._add_sheet()

def _add_sheet(self):
if self.sheetindex != 0:
# This method is used to save the Workbook to a file in native Excel format.
self.bk.save(self.name + str(self.sheetindex) + ".xls")
# create new workbook
if self.sheetindex > MAX_SHEET_NUM:
self.workbookIndex += 1
self.bk = xlwt.Workbook(encoding=self.encoding, style_compression=0)
self.sheetindex = 1
# a new sheet
index=self.sheetindex
print("self.sheet_index=",index)
self.sheet = self.bk.add_sheet(self.name +
index.__str__(),
cell_overwrite_ok=False)
for i in range(len(self.captionlist)):
# This method is used to write a cell to a :class:`Worksheet`
self.sheet.write(0, i, self.captionlist[i])

self.row = 1

def write(self, data: list):
"""
:type data: list
"""
# The row of current sheet > the max rows of sheet then create a new sheet
if self.row > MAX_ROW_NUM:
self.sheetindex += 1
self._add_sheet()
self._add_sheet()
for i in data:
for j in range(len(i)):
if self.typeList[j] == "num":
try:
self.sheet.write(self.row, j, float(i[j]))
except:
raise ValueError("{} is not a number".format(i[j]))
else:
self.sheet.write(self.row, j, i[j])
# when rows =1000 then flush rows
if self.row % self.flushBound == 0:
self.sheet.flush_row_data()
self.row += 1

@staticmethod
def __find_file(keyword):
for root, d, files in os.walk(ConfigENum.DATA_PATH.value):
for file in files:
if keyword in file:
file = os.path.join(root, file)
return file
return False

def add_write(self, datas):

result=self.__find_file(self.name)
if not result:
self.write(datas)
self.save()
return "ok"

if self.row > MAX_ROW_NUM:
self.sheetindex += 1
self._add_sheet()

# read a excel file
self.bk = open_workbook(result)
# get the rows of sheet
rows = self.bk.sheets()[self.sheetindex].nrows
# Copy an :class:`xlrd.Book` into an :class:`xlwt.Workbook`
excel = copy(self.bk)

self.sheet = excel.get_sheet(self.sheetindex)
self.row = rows
for data in datas:
# [1,2,3,4]
for j in range(len(data)):
self.sheet.write(self.row, j, data[j]) # xlwt对象的写方法,参数分别是行、列、值
if self.row % self.flushBound == 0:
self.sheet.flush_row_data()
self.row += 1
self.excel_name = os.path.join(ConfigENum.DATA_PATH.value,
self.name + self.workbookIndex.__str__() + ".xls")
excel.save(self.excel_name)


def save(self):
self.excel_name = os.path.join(ConfigENum.DATA_PATH.value,
self.name + self.workbookIndex.__str__() + ".xls")
self.bk.save(self.excel_name)
# if __name__ == "__main__":

# caption_list = ["name", "gender", "age"]
# type_list = ["str", "str", "num"]
# input_data = ["Lili", "M", 25]
# excl=XLS("test",caption_list,type_list)
# excl.write(input_data)
# excl.save()

posted @ 2018-11-09 11:11  tny_leyon  阅读(5573)  评论(0编辑  收藏  举报