|
| 1 | +import argparse |
| 2 | +import base64 |
| 3 | +import openpyxl |
| 4 | +import os |
| 5 | +import json |
| 6 | +import webbrowser |
| 7 | +from urllib.parse import quote |
| 8 | + |
| 9 | + |
| 10 | +def base64_to_file(s, filename): |
| 11 | + """Convert base64-encoded string to file. |
| 12 | +
|
| 13 | + Parameters |
| 14 | + ---------- |
| 15 | + s : str |
| 16 | + base64encoded string |
| 17 | + filename : str |
| 18 | + filename of file |
| 19 | + """ |
| 20 | + file = open(filename, 'wb') |
| 21 | + file.write(base64.b64decode(s)) |
| 22 | + file.close() |
| 23 | + |
| 24 | + |
| 25 | +def excel_append_line(filename, linedata, sheet_idx=0): |
| 26 | + """Append list as newline to excel sheet. |
| 27 | +
|
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + filename : str |
| 31 | + filename of xlsx-file |
| 32 | + linedata : list |
| 33 | + list, which will be appended as new line in sheet |
| 34 | + sheet_idx : int |
| 35 | + index of sheet, where to append linedata |
| 36 | + """ |
| 37 | + workbook = openpyxl.load_workbook(filename) |
| 38 | + sheet = workbook[workbook.get_sheet_names()[0]] |
| 39 | + sheet.append(linedata) |
| 40 | + workbook.save(filename) |
| 41 | + |
| 42 | + |
| 43 | +def main(): |
| 44 | + # argument parser |
| 45 | + parser = argparse.ArgumentParser() |
| 46 | + parser.add_argument('filecontents', |
| 47 | + help='Base64-encoded string of xlsx-file.') |
| 48 | + parser.add_argument('linecontent', nargs='+', |
| 49 | + help='Content of line to be appended in xlsx-file.') |
| 50 | + parser.add_argument('-f', '--filepath', type=str, |
| 51 | + help='Filename and path for Excel file.') |
| 52 | + parser.add_argument('-i', '--index', type=int, default=0, |
| 53 | + help='Sheet index of Excel file.') |
| 54 | + args = parser.parse_args() |
| 55 | + |
| 56 | + # define filename for temporary file |
| 57 | + filename = 'tmp.xlsx' |
| 58 | + |
| 59 | + # convert base64-encoded file |
| 60 | + base64_to_file(args.filecontents, filename) |
| 61 | + |
| 62 | + # append data to file |
| 63 | + excel_append_line(filename, args.linecontent, sheet_idx=args.index) |
| 64 | + |
| 65 | + # encode newly generated file to base64 and remove temporary file |
| 66 | + file = open(filename, 'rb') |
| 67 | + workflow_input = {'filecontents': base64.b64encode(file.read()) |
| 68 | + .decode('ascii')} |
| 69 | + file.close() |
| 70 | + os.remove(filename) |
| 71 | + |
| 72 | + # add filepath to dict if available |
| 73 | + if args.filepath is not None: |
| 74 | + workflow_input['path'], \ |
| 75 | + workflow_input['filename'] = os.path.split(args.filepath) |
| 76 | + |
| 77 | + # pass data back to Workflow |
| 78 | + webbrowser.open('workflow://run-workflow?name=SaveBase64ToDropbox&input=' + |
| 79 | + quote(json.dumps(workflow_input), '')) |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == '__main__': |
| 83 | + main() |
| 84 | + |
0 commit comments