本文所使用的的平台为pycharm(注意:pycharm非正版授权的用户不能对pycharm进行更新升级,否则会导致pycharm授权文件失效无法使用,如果不慎升级可卸载重装解决。本文作者坚决打击盗版,支持正版授权。)
本文提供两种思路供大家参考:
import xlwt
import openpyxl
from openpyxl import Workbook, workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter
def copy_and_stick(m,n):
wb = load_workbook('E:\\PythonProgram\\test_new.xlsx')
ws = wb['网级数据']# sheet名称
sheet = wb.active
a = sheet.max_row
b = []
i = 0
while i < a:
i = i + 1
print(ws.cell(i, m).value)
b.insert(i, ws.cell(i, m).value)
wbtest = load_workbook('E:\\PythonProgram\\test1.xlsx')# 目标路径
ws = wbtest['Sheet1']
sheet = wb.active
i = 1
while i < a:
ws.cell(i + 1, n).value = b[i]
i = i + 1
wbtest.save('E:\\PythonProgram\\test1.xlsx')# 保存关闭
# 写入jp_bci_valid2021
copy_and_stick(1,3)
# copy_and_stick(2,5)
# 重新读取,写入列名
wbtest1 = load_workbook('E:\\PythonProgram\\test1.xlsx')
sheet = wbtest1.active
ws = wbtest1['Sheet1']
col = ["fd_objectid", "pavementtype", "vehiclelane", "roadcode", "upanddown",
"acquisitiondate", "years", "num", "roadstart", "roadends",
"province_code", "city_code", "county_code", "town_code"]
j = 1
for i in col:
sheet.cell(row=1, column=j, value=i)
j = j + 1
savepath = 'E:\\PythonProgram\\test1.xlsx'
wbtest1.save(savepath)
这种方法采用函数的形式来对表格进行复制粘贴工作,读取表格m列,粘贴到另一表格第n列,注意在调用一些方法是会调用Anaconda库内容,记得配置好,不然前几行会报错。
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter
import xlrd
# 待处理表格路径
wb = load_workbook (r"E:\PythonProgram\道网级数据.xlsx")
# 表单名称
ws = wb['网级数据排序(公式)']
sheet = wb.active
a = sheet.max_row
# 字段字典
dict_jp_bci_valid={'路面类型': 'pavementtype', '路线代码':'roadcode', '起点桩号': 'roadstart',
'终点桩号': 'roadends', '行政区划':'deptcode', '技术等级': 'grade',
}
# 复制表格路径
wbtest = load_workbook (r"E:\PythonProgram\tci_valid.xlsx") # 修改*****
# 表单名称
wss = wbtest['tci_valid']# 修改*****
sheet1 = wbtest.active
# 读取列名
data = []
k = 0
for i in wbtest['tci_valid'][1]: # 'Sheet1'为表单名称, 1 为第一行修改*******
data.insert(k,i.value)
k += 1
d = []
e = 0
for z in wb['网级数据'][1]: # 'Sheet1'为表单名称, 1 为第一行
d.insert(e,z.value)
e += 1
i = 0
j = 1
for item in dict_jp_bci_valid.items():
key = item[0]
value1 = item[1]
for codeindex in d:
if key == codeindex:
f = d.index(codeindex)
hanzi = f + 1# 获取表格对应位置
b = []
while i < a:
i = i + 1
print(ws.cell(i,hanzi).value)
b.insert(i, ws.cell (i,hanzi).value)# 写入一列数据到b
code = dict_jp_bci_valid[key]
for cel in data:# 目标列名
if value1 == cel:
c = data.index(cel) # 获取目标位置
j = 1
i = 1
while j < a:
wss.cell (j+1,c+1).value = b[i]# 粘贴到对应位置
j = j + 1
i = i + 1
b.clear()# 清空列表
i = i - i# 行归零
# 保存路径
wbtest.save (r"E:\PythonProgram\Etci_valid.xlsx")# 修改*****
这种方法利用字典将列名进行匹配,然后将相匹配的列内容放进去,前提是要先准备好两张表中的列名。