I tried to build a Python program that takes in Excel, edits it, and outputs Excel and CSV files.
① Import sample.xlsx ② Edit ③ Output sample2.xlsx and sample.csv
The program is studded with comments, so please check that.
After that, it would be perfect if we could make the work more efficient by applying this and letting Python do the work.
file_edit.py
import pathlib
import openpyxl
import csv
#Get excel file
wb = openpyxl.load_workbook("./data/sample.xlsx")
#Get sheet "Name: Sheet1"
ws = wb["Sheet1"]
#Output data in cell A1 * Pattern 1
print(ws["A1"].value) #Get by specifying cell A1
#Output data in cell A1 * Pattern 2
row1 = ws[1] #Get the first line of sheet "Name: Sheet1"
print(row1[0].value) #Get the 1st row and 1st column ⇒ As a result, cell A1
#Output all data
print("All data>")
for row in ws.rows:
for cell in row:
print(cell.value)
#Rewrite data in cell A1
ws["A1"].value = "★ A1"
#Save the loaded Excel with a different name
#* In case of overwriting, specify the read file path
wb.save("./data/sample2.xlsx")
#Output CSV file
with open("./data/csvsample.csv", "w", encoding="utf_8_sig") as fp:
writer = csv.writer(fp, lineterminator="\n")
for row in ws.rows:
writer.writerow([col.value + "csv" for col in row])
Recommended Posts