#xlsx表格追加追加内容
#1.单个表追加内容
import xlrd as ExcelRead
from xlutils.copy import copy
import os
import xlwt
def write_append(file_name,lists): #xlsx表格追加
if not os.path.exists(file_name):
f = xlwt.Workbook()
sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True)
row0=['分类','品名','净含量','保存条件']
for i in range(0, len(row0)):
sheet1.write(0, i, row0[i])
f.save(file_name)
r_xls = ExcelRead.open_workbook(file_name)
r_sheet = r_xls.sheet_by_index(0)
rows = r_sheet.nrows
w_xls = copy(r_xls)
sheet_write = w_xls.get_sheet(0)
for index,values in enumerate(lists):
for i in range(0, len(values)):
sheet_write.write(rows+index, i, values[i])
w_xls.save(file_name)
lists= [["Ann", "woman", 22, "UK"],["Ann", "woman", 22, "UK"],["Ann", "woman", 22, "UK"],["Ann", "woman", 22, "UK"]]
write_append("job1.xlsx",lists)
#2.向多个表追加内容
import xlrd as ExcelRead
from xlutils.copy import copy
import xlwt
def write_append(file_name,sheet_name,sheet_index,values):
"""
:param file_name: 文件名
:param sheet_name: 表名
:param sheet_index: 表索引
:param values: list数据
"""
r_xls = ExcelRead.open_workbook(file_name)
r_sheet = r_xls.sheet_by_name(sheet_name)
rows = r_sheet.nrows
w_xls = copy(r_xls)
sheet_write = w_xls.get_sheet(sheet_index)
for i in range(0, len(values)):
sheet_write.write(rows, i, values[i])
w_xls.save(file_name)
if __name__ == '__main__':
sheets=['sheet1', 'sheet2']
if not os.path.exists('facebook.xlsx'):
title = ['帖子id', '标题', '发布时间', '点赞数', '爬取时间','帖子链接']
f = xlwt.Workbook()
for i in sheets:
sheet1 = f.add_sheet(i,cell_overwrite_ok=True) #添加表
for i in range(0, len(title)):
sheet1.write(0, i, title[i])
f.save('facebook.xlsx')
for v in sheets:
sheet_index=sheets.index(v)
values=['帖子id', '标题', '发布时间', '点赞数', '爬取时间','帖子链接'] #写入的数据
write_append('facebook.xlsx',v,sheet_index, values)