python 拆分excel工作表_Python合并拆分excel

Python 实现合并

defmerge_excel(dir):print('--- 执行合并 ---')

filename_excel= [] #存表名

frames = [] #存表内容

d = dir.replace('/','\\\\') #因pandsa读取路径为双斜杠,需转换

if d.endswith('\\\\') == False: #若为磁盘根目录则路径结尾自带\\,若为文件夹则无,需添加\\

d = d + '\\\\'

print("路径是:",d,"\n有以下文件:")for files in os.listdir(path=dir): #遍历目录下的文件

print(files)if 'xlsx' in files or 'xls' in files : #搜索xlsx/xls后缀文件

filename_excel.append(files)

df= pd.read_excel(d+files) #读取一个表内容存入一个DataFrame

frames.append(df)if len(frames)!= 0: #若存在EXCEL表则合并保存

result = pd.concat(frames) #上下连接多个df

result.to_excel(d+"合并结果表.xlsx")

merge_excel("D:/某文件夹")

Python 实现拆分

defsplit_excel(path,num):#print("--- 执行拆分 ---")

p = path.replace('/', '\\\\') #传入pd库read_excel方法的路径,含文件名

dir = p[ : p.rfind('\\') + 1 ] #输出被拆分表的目录,不含文件名

sheetname = path[ path.rfind('/') + 1 :].strip('.xlsx').strip('.xlx') #无后缀的文件名

data = pd.read_excel(p) #数据

nrows = data.shape[0] #获取行数

split_rows = num #自定义要拆分的条数,即分隔成多少行一份

count = int(nrows/split_rows) + 1 #拆分的份数

#print("应当拆分成%d份"%count)

begin =0

end=0for i in range(1,count+1):

sheetname_temp= sheetname+str(i)+'.xlsx' #拆分后的每个表名

if i == 1:

end=split_rowselif i ==count:

begin=end

end=nrowselse:

begin=end

end= begin +split_rowsprint(sheetname_temp)

data_temp= data.iloc[ begin:end , : ] #[ 行范围 , 列范围 ]

data_temp.to_excel(dir +sheetname_temp)#print('拆分完成')

split_excel("test.xlsx",5)

以上转自:https://mp.weixin.qq.com/s/0qwnhY5t_FPBFEEDvEuYiA

Python 操作PDF的几种方法(合并、拆分、水印、加密)

一、前言

大家好,有关Python操作PDF的案例之前已经写过一个👉PDF批量合并,这个案例初衷只是给大家提供一个便利的脚本,并没有太多讲解原理,其中涉及的就是PDF处理很实用的模块PyPDF2,本文就好好剖析一下这个模块,主要将涉及

os模块综合应用

glob模块综合应用

PyPDF2模块操作

二、基本操作

PyPDF2 导入模块的代码常常是:

from PyPDF2 import PdfFileReader, PdfFileWriter

这里导入了两个方法:

PdfFileReader可以理解为读取器

PdfFileWriter可以理解为写入器

from PyPDF2 importPdfFileReader, PdfFileWriter

path= r'C:\Users\xxxxxx'pdf_writer=PdfFileWriter()for i in range(1, 6):

pdf_reader= PdfFileReader(path + '/INV{}.pdf'.format(i))for page inrange(pdf_reader.getNumPages()):

pdf_writer.addPage(pdf_reader.getPage(page))

with open(path+ r'\合并PDF\merge.pdf', 'wb') as out:

pdf_writer.write(out)

from PyPDF2 importPdfFileReader, PdfFileWriter

path= r'C:\Users\xxx'pdf_reader= PdfFileReader(path + '\INV1.pdf')for page inrange(pdf_reader.getNumPages()):#遍历到每一页挨个生成写入器

pdf_writer =PdfFileWriter()

pdf_writer.addPage(pdf_reader.getPage(page))#写入器被添加一页后立即输出产生pdf

with open(path + '\INV1-{}.pdf'.format(page + 1), 'wb') as out:

pdf_writer.write(out)

以上转自:https://mp.weixin.qq.com/s/YOunnZoOMvH-Ga13vq3xvg

importosfrom PyPDF2 importPdfFileReader, PdfFileWriterdefGetFileName(dir_path):

file_list=[os.path.join(dirpath, filesname) \for dirpath, dirs, files inos.walk(dir_path) \for filesname infiles]returnfile_listdefMergePDF(dir_path, file_name):

output=PdfFileWriter()

outputPages=0

file_list=GetFileName(dir_path)for pdf_file infile_list:print("文件:%s" % pdf_file.split('\\')[-1], end=' ')#读取PDF文件

input = PdfFileReader(open(pdf_file, "rb"))#获得源PDF文件中页面总数

pageCount =input.getNumPages()

outputPages+=pageCountprint("页数:%d" %pageCount)#分别将page添加到输出output中

for iPage inrange(pageCount):

output.addPage(input.getPage(iPage))print("\n合并后的总页数:%d" %outputPages)#写入到目标PDF文件

print("PDF文件正在合并,请稍等......")

with open(os.path.join(dir_path, file_name),"wb") as outputfile:#注意这里的写法和正常的上下文文件写入是相反的

output.write(outputfile)print("PDF文件合并完成")if __name__ == '__main__':#设置存放多个pdf文件的文件夹

dir_path = r'C:\Scientific Research\Knowladge\Ophthalmology\Chinese Ophthalmology'

#目标文件的名字

file_name = "中华眼科学(第3版)合并版.pdf"MergePDF(dir_path, file_name)

以上转自:https://mp.weixin.qq.com/s/ZlgpWMKpex9Iu2o64r077A

Python办公自动化|从Word到Excel

#导入需要的库docx

from docx importDocument#指定文件存放的路径

path = r'C:\Users\word.docx'

#读取文件

document =Document(path)#读取word中的所有表格

tables = document.tables

# 获取第一张表

table0 = tables[0]

#在全局放一个变量用来计数填序号

n =0for i in range(0, len(table0.rows) + 1, 3):#日期

date = table0.cell(i, 1).text#标题

title = table0.cell(i + 1, 1).text.strip()#文号

dfn = tables[j].cell(i, 3).text.strip()print(n, date, tite, dfn)

importdatetime

n=0for i in range(0, len(table0.rows) + 1, 3):#日期

date = table0.cell(i, 1).text#有的条目时间是空的,这里不做过多判别

if '/' indate:

date= datetime.datetime.strptime(date, '%d/%m').strftime('2020-%m-%d')else:

date= '-'

#标题

title = table0.cell(i + 1, 1).text.strip()#文号

dfn = tables[j].cell(i, 3).text.strip()print(n, date, tite, dfn)

n =0for j inrange(len(tables)):for i in range(0, len(tables[j].rows)+1, 3):try:#日期

date = tables[j].cell(i, 1).textif '/' indate:

date= datetime.datetime.strptime(date, '%d/%m').strftime('2020-%m-%d')else:

date= '-'

#标题

title = tables[j].cell(i + 1, 1).text.strip()#文号

dfn = tables[j].cell(i, 3).text.strip()

n+= 1

print(n, date, title, dfn)exceptException as error:#捕获异常,也可以用log写到日志里方便查看和管理

print(error)continue

from openpyxl importWorkbook#实例化

wb =Workbook()#获取当前sheet

sheet =wb.active#设立表头

header = ['序号', '收文时间', '办文编号', '文件标题', '文号', '备注']

sheet.append(header)

row = [n, date,' ', title, dfn,' ']

sheet.append(row)

线程的最后记得保存

wb.save(r'C:\Users\20200420.xlsx')

from docx importDocumentimportdatetimefrom openpyxl importWorkbook

wb=Workbook()

sheet=wb.active

header= ['序号', '收文时间', '办文编号', '文件标题', '文号', '备注']

sheet.append(header)

path= r'C:\Users\word.docx'document=Document(path)

tables=document.tables

n=0for j inrange(len(tables)):for i in range(0, len(tables[j].rows)+1, 3):try:#日期

date = tables[j].cell(i, 1).textif '/' indate:

date= datetime.datetime.strptime(date, '%d/%m').strftime('2020-%m-%d')else:

date= '-'

#标题

title = tables[j].cell(i + 1, 1).text.strip()#文号

dfn = tables[j].cell(i, 3).text.strip()

n+= 1

print(n, date, title, dfn)

row= [n, date, ' ', title, dfn, ' ']

sheet.append(row)exceptException as error:#捕获异常,也可以用log写到日志里方便查看和管理

print(error)continuewb.save(r'C:\Users\20200420.xlsx')

以上转自:https://mp.weixin.qq.com/s/Gry1gjz-ZmKyQOFoEnOm3g

from openpyxl importload_workbook, Workbookimportglob

path= 'C:/Users/xxxxxx'new_workbook=Workbook()

new_sheet=new_workbook.active#用flag变量明确新表是否已经添加了表头,只要添加过一次就无须重复再添加

flag =0for file in glob.glob(path + '/*.xlsx'):

workbook=load_workbook(file)

#打开已经存在的Excel用load_workbook,创建新的Excel用Workbook

sheet=workbook.active

buy_mount= sheet['F'] row_lst=[]for cell inbuy_mount:if isinstance(cell.value, int) and cell.value > 50:print(cell.row)

row_lst.append(cell.row)if notflag:

# 创建和 电商婴儿数据 一样的表头(第一行)

header= sheet[1]

header_lst=[]for cell inheader:

header_lst.append(cell.value)

new_sheet.append(header_lst)

flag= 1

# 从旧表中根据行号提取符合条件的行,并遍历单元格获取值,以列表形式写入新表

for row inrow_lst:

data_lst=[]for cell insheet[row]:

data_lst.append(cell.value)

new_sheet.append(data_lst)

new_workbook.save(path+ '/' + '符合筛选条件的新表.xlsx')

注意这一列有可能有的单元格cell的值value不是数值类型,因此需要用isinstance()进行判断,当然也可以将单元格的值先用int()转为整型再判断。

以上转自:https://mp.weixin.qq.com/s/RD3h6vJe7_aSPwCpU1p9Ig

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值