这次尝试用openpyxl模块来处理
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
# 新建一个workbook
wb_dst = Workbook()
# 文件的输出路劲以及名字
dst_filename = r'dest10.xlsx'
# 设置写入的sheet
ws_dst = wb_dst.worksheets[0]
# 打开源文件
wb1 = load_workbook(r"********.xlsx")
sheetnames = wb1.get_sheet_names()
table_1 = wb1.get_sheet_by_name(sheetnames[1])
print(table_1.title)
# 获取源文件sheet的行数
rownum = table_1.max_row
print(rownum)
# 定位目标文件的写入初始位置
i = 0
# 对excel单元格追加数据
def append_to_cell(location, text, sheet):
print(sheet[location].value)
if sheet[location].value == None:
new = text
else str(sheet[location].value) != None:
new = str(sheet[location].value) + text
sheet[location].value= new
return
# 逐行遍历
for row in range(1, rownum):
cell_name = "{}{}".format("A", row)
# name不为空代表时一个个体,在dest10中写入一行
if table_1[cell_name].value != None:
i += 1
ws_dst["%s%s"%("A", i)].value = table_1[cell_name].value
ws_dst["%s%s" % ("B", i)].value = table_1["%s%s"%("C", row)].value
if table_1["%s%s"%("D", row)].value != None:
append_to_cell("%s%s" % ("D", i), table_1["%s%s"%("D", row)].value, ws_dst)
if table_1["%s%s"%("E", row)].value != None:
append_to_cell("%s%s" % ("E", i), table_1["%s%s" % ("E", row)].value, ws_dst)
if table_1["%s%s"%("F", row)].value != None:
append_to_cell("%s%s" % ("F", i), table_1["%s%s" % ("F", row)].value, ws_dst)
# name为空时,把table_1的数据追加在已有数据的行中
else:
if table_1["%s%s"%("D", row)].value != None:
append_to_cell("%s%s" % ("D", i), table_1["%s%s"%("D", row)].value, ws_dst)
if table_1["%s%s"%("E", row)].value != None:
append_to_cell("%s%s" % ("E", i), table_1["%s%s" % ("E", row)].value, ws_dst)
if table_1["%s%s"%("F", row)].value != None:
append_to_cell("%s%s" % ("F", i), table_1["%s%s" % ("F", row)].value, ws_dst)
# 保存写入数据文件
wb_dst.save(filename=dst_filename)
openpyxl:支持xlsx写入,写入以execl的绝对坐标值定位,例如:A3。
xlrd、xlwt:不支持xlsx写入。写入时坐标以(0,0)开始