通过Python实现快速合并内容相似的Excel文件要怎么做

2021-04-08 10:39发布

2条回答
aijingda
2楼 · 2021-04-09 10:22

下面这段简单的Python代码就可以实现合并:

app='Word'
word=win32.gencache.EnsureDispatch('%s.Application' % app) 
doc=word.Documents.Add() 
word.Visible=False
  
#Title begin  
sel =word.Selection 
sel.Font.Name = u"微软雅黑"
sel.Font.Size = 8  
sel.Font.Bold = False 
sel.Font.Italic = False
sel.Font.Underline = False
sel.ParagraphFormat.Alignment = 1
  
myRange = doc.Range(0,0) 
myRange.InsertBefore(u'标题1 测试表格') # 使用样式 
#Title end 
#Table Start 
sel.SetRange(10,10) 
tab = doc.Tables.Add(sel.Range, 9, 3) 
tab.Columns(1).SetWidth(10.35*20.35, 0) 
tab.Rows.Alignment = 1
tab.Style = u"网格型"
tabnow = doc.Tables(1) 
cell1 = tabnow.Cell(1,1) 
cell2 = tabnow.Cell(3,1) 
  
#myrange = doc.Range(cell1.Range.Start, cell2.Range.End) 
  
sel.SetRange(cell1.Range.Start, cell2.Range.End) 
sel.Cells.Merge()

很简单吧~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding:utf-8 -*-
import os, xlrd, xlsxwriter
source_dir = r'input'
new_execl = "All in one.xlsx"
raw_excels = os.listdir(source_dir)
keyword = "油站经理" # 除包括此关键字的行均插入
data = []
filename = os.path.join(source_dir, raw_excels[0])
wb = xlrd.open_workbook(filename)
sheet = wb.sheets()[0]
data.append(sheet.row_values(0))
data.append(sheet.row_values(1))
for excel in raw_excels:
 filename = os.path.join(source_dir, excel)
 wb = xlrd.open_workbook(filename)
 sheet = wb.sheets()[0]
 for row_num in range(2, sheet.nrows):
  row_values = [str(i) for i in sheet.row_values(row_num)]
  if len(''.join(row_values)) and (keyword not in ''.join(row_values)):
   data.append(sheet.row_values(row_num))
data.append(sheet.row_values(sheet.nrows-1))
new_wb = xlsxwriter.Workbook(new_execl)
worksheet = new_wb.add_worksheet()
font = new_wb.add_format({"font_size":11})
for i in range(len(data)):
 for j in range(len(data[i])):
  worksheet.write(i, j, data[i][j], font)
new_wb.close()