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()

原文地址:https://www.cnblogs.com/tnyleyon/p/9933985.html

时间: 2024-10-11 06:32:43

python excel写入及追加写入的相关文章

Python Excel 多sheet 多条数据 自定义写入

pip install xlwt python excel 数据写入操作,处理网站数据导出以及不是太多数据的爬虫存储, 用处蛮多的轮子. (150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=) 1 #

Java读取txt文件和覆盖写入txt文件和追加写入txt

package thread; import java.io.*; public class hh { /** * 创建文件 * @param fileName * @return */ public static boolean createFile(File fileName)throws Exception{ try{ if(!fileName.exists()){ fileName.createNewFile(); } }catch(Exception e){ e.printStackT

EXCEL页面数据快速写入SQL数据库

将EXCEL数据存入SQL表, 一万行记录大概5秒 Dim conn As New ADODB.Connection Dim CNN As New ADODB.Connection 'Dim rst As New ADODB.Recordset Dim Sql As String Dim j, v As Integer Const cnnstr = "Provider = SQLOLEDB;" & _ "Data Source = ip;" & _

Java基础知识强化之IO流笔记20:FileOutputStream写出数据实现换行和追加写入

1.  如何实现数据的换行? (1) 1 package com.himi.fileoutputstream; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 8 /** 9 * 10 * 如何实现数据换行? 11 * 12 */ 13 14 15 public class FileOutputStreamDemo4 { 1

ObjectOutputStream 追加写入读取错误

摘自http://blog.csdn.net/mitkey/article/details/50274543 问题描述: 用类ObjectOutputStream向文件写读对象时,碰到一个问题:新建一个文件,用输出流ObjectOutputStream向文件连续写几个对象,关闭输出流,然 后读取,这些对象都可以读出:这时在向该文件增加对象,新写的对象就读不出了 问题出现的原因: ObjectOutputStream建立后第一次写入一个对象时, 会在对象数据前写入一些标志的数据"AC ED  00

C#学习笔记(22)——C#创建文本文件txt并追加写入数据

说明(2017-7-31 16:25:06): 1. 有两种办法,第一种是用FileStream创建txt,用StreamWriter写入数据,期间还要加上判断,是否存在这个txt文件,如果不存在就创建,存在就追加写入.太麻烦了! 2. 第二种是直接File.AppendAllText(string path, string contents);第一个参数是txt路径+文件名,第二个参数是写入内容.这个方法会自己判断文件是否存在,直接一步到位! using System; using Syste

C# FileStream Write追加写入文本(转载)

转自: http://blog.csdn.net/andrew_wx/article/details/6629913 该例子为追加 C盘中的 file1.txt 的文本内容 完整代码如下: 引入命名空间: using System.IO; 完整代码: namespace FileStreamWrite { class Program { static void Main(string[] args) { FileStream fs = null; string filePath = "C:\\f

PHP 文件写入或追加数据

PHP file_put_contents() 函数是一次性向文件写入字符串或追加字符串内容的最合适选择. file_put_contents() file_put_contents() 函数用于把字符串写入文件,成功返回写入到文件内数据的字节数,失败则返回 FALSE. 语法: int file_put_contents ( string filename, string data [, int flags [, resource context]] ) 参数说明: 参数 说明 filenam

用python在后端将数据写入到数据库并读取

用python在后端将数据写入到数据库: # coding:utf-8 import pandas as pd from sqlalchemy import create_engine # 初始化数据库连接,使用pymysql模块 # MySQL的用户:root, 密码:147369, 端口:3306,数据库:mydb engine = create_engine('mysql+pymysql://root:[email protected]:3306/python1') import nump