python excel写入及追加写入

Posted tny_leyon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()


































































































以上是关于python excel写入及追加写入的主要内容,如果未能解决你的问题,请参考以下文章

python pandas在已存在的excel中追加数据

python 求excel每列平均值并追加写入到最后一行 读取 修改 表格

用python模糊检索EXCEL文件的内容,并写入新的EXCEL表?

python openpyxl模块实现excel的读取,新表创建及原数据表追加新数据

POI向Excel中写入数据及追加数据

python连接mysql之查询及写入excel