Skip to content

Instantly share code, notes, and snippets.

@arsane
Created September 15, 2015 08:30
Show Gist options
  • Save arsane/b16e54553dd8990acec8 to your computer and use it in GitHub Desktop.
Save arsane/b16e54553dd8990acec8 to your computer and use it in GitHub Desktop.
a python script to copy specified columns from one excel to another.
#!/usr/bin/python
from string import ascii_uppercase
from sys import argv
from os.path import splitext
from openpyxl import Workbook, load_workbook
S_KEY_COL = "A"
L_COLS_FILL = ["C", "D"]
N_ROW_START = 15
def coord(c, r):
return c + str(r+1)
def merge_file(src, dest):
book_src, book_dst = map(lambda x : load_workbook(x), [src, dest])
sheet_src, sheet_dst = map(lambda x : x.active, [book_src, book_dst])
dict_case_row = {}
# construct the dictionary for "case -> row_num" in the source excel file
for i in range(N_ROW_START, len(sheet_src.rows)):
key = sheet_src.cell(coord(S_KEY_COL, i)).value
if key in dict_case_row:
print "more than one result for case ", key
return 1
dict_case_row[ key ] = i
# merge value from dst.
for i in range(N_ROW_START, len(sheet_dst.rows)):
cell = sheet_dst.cell(coord(S_KEY_COL, i))
if cell.value not in dict_case_row:
print "error: can't find case ", cell.value
return 1
else:
# set the hyper link because openpyxl can't handle hyper link properly.
n = dict_case_row[cell.value]
cell.hyperlink = cell.value
for col in L_COLS_FILL:
sheet_dst.cell(coord(col, i)).value = sheet_src.cell(coord(col, n)).value
# save excel file to new file.
book_dst.save('.out'.join(splitext(dest)))
return 0
if __name__ == "__main__":
if len(argv) == 1:
print "Help:", argv[0], "[src file] [dest file]"
exit(1)
exit(merge_file(argv[1], argv[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment