代码如下
import openpyxl
q = 0 # 单元格个数
k = 0 # 列表下标
lists = []
sum_row = 0 # 新文件的行数
sum_column = 0 # 新文件的列数
beagin_row = input(“从第几行开始:”)
beagin_column = input(“从第几列开始:”)
while True:
file_row = 0 # 读取文件的行数
file_column = 0 # 读取文件的列数
file_name = input("请输入文件名,按q退出:")
if file_name == 'q':
break
wb = openpyxl.load_workbook(file_name+'.xlsx')
sheet1 = wb.get_sheet_by_name('Sheet1')
while True: # 计算文件行数
if sheet1.cell(row=file_row + int(beagin_row), column=int(beagin_column)).value is not None:
file_row = file_row + 1
else:
break
sum_row = file_row + sum_row
while True: # 计算文件列数
if sheet1.cell(row=int(beagin_row), column=file_column + int(beagin_column)).value is not None:
file_column = file_column + 1
else:
break
sum_column = file_column
print(file_row, file_column)
print(sum_row, sum_column)
for i in range(int(beagin_row), sheet1.max_row): # 从第4行开始
for j in range(int(beagin_column), sheet1.max_column): # 从第一列开始
x = sheet1.cell(row=i, column=j).value # 取出单元格的值
if x is not None:
q = q+1 # 单元格个数
lists.append(x) # 将单元格内容添加到列表中存储
file_save = input(“请输入保存文件名:”)
wb1 = openpyxl.Workbook(file_save + ‘.xlsx’)
wb1.create_sheet(index=0, title=‘Sheet1’)
wb1.save(file_save + ‘.xlsx’)
wb2 = openpyxl.load_workbook(file_save +’.xlsx’)
sheet2 = wb2.get_sheet_by_name(‘Sheet1’)
while k < q:
for i in range(1, sum_row+1): # 循环行数
for j in range(1, sum_column+1): # 循环列数
sheet2.cell(row=i, column=j).value = lists[k]
k = k+1
wb2.save(file_save + ‘.xlsx’)