The project outline:
Write a program that performs the tasks of the previous program in reverse order: the program should open a spreadsheet and write the cells of column A into one text file, the cells of column B into another text file, and so on.
My solution:
# A program to read a spreadsheet and write it to a text file with one text file per column
# Usage: python spreadsheet_to_text.py "spreadsheet path" "folder to save .txt files"
import sys, openpyxl
from pathlib import Path
from openpyxl.utils import get_column_letter
def main(spreadsheet_path, save_folder):
workbook = openpyxl.load_workbook(spreadsheet_path)
sheet = workbook.active
for column_index in range(1, sheet.max_column + 1):
file_path = save_folder / f"Text for column {get_column_letter(column_index)}.txt"
with open(file_path, "w", encoding="utf-8") as text_file:
for row_index in range(1, sheet.max_row + 1):
cell = sheet.cell(row=row_index, column=column_index)
if not cell.value:
text_file.write("\n")
else:
text_file.write(str(cell.value) + "\n")
if __name__ == "__main__":
spreadsheet_path = Path(sys.argv[1]) # The location of the spreadsheet to open
save_folder = Path(sys.argv[2]) # The path of the folder to save the .txt files in
main(spreadsheet_path, save_folder)
I decided to copy the formulas themselves rather than the result because the outline doesn't specify and the chapter doesn't discuss it.