Excel Cheatsheet
Excel Cheatsheet
🛠 LIBRARIES:
-------------
1. python-docx → Create and modify Word files
2. pandas → Load, filter, and manipulate Excel data
3. openpyxl → Used by pandas to read/write Excel files
=========================
📦 INSTALLATION
=========================
pip install python-docx pandas openpyxl
=========================
📚 WORD DOCX (python-docx)
=========================
from docx import Document
📌 Access paragraphs:
for para in doc.paragraphs:
print(para.text)
📌 Replace text:
para.text = para.text.replace("old", "new")
📌 Add paragraph:
doc.add_paragraph("Hello world")
📌 Add heading:
doc.add_heading("Title", level=1)
📌 Add a table:
table = doc.add_table(rows=1, cols=3)
table.style = 'Table Grid'
=========================
📚 EXCEL (pandas + openpyxl)
=========================
import pandas as pd
📌 Read Excel:
df = pd.read_excel("data.xlsx")
📌 Save Excel:
df.to_excel("new_file.xlsx", index=False)
📌 Show columns:
print(df.columns)
📌 Filter rows:
df[df["]"فني شبكات" == ]"الوظيفة
📌 Select columns:
df[[" "التاريخ,"]]"االسم
📌 Slice rows:
df.iloc[0:4]
📌 Modify values:
df[" = ]"التاريخdf["]"التاريخ.astype(str)
📌 Sort rows:
df.sort_values(")"التاريخ
📌 Remove rows:
df = df.drop([0, 1]) # by index
📌 Remove duplicates:
df = df.drop_duplicates()
=========================
🧩 COMPLETE WORD + EXCEL EXAMPLE
=========================
from docx import Document
import pandas as pd
df = pd.read_excel("data.xlsx")
doc = Document("template.docx")
group = df.iloc[0:4]["]"االسم.tolist()
for i in range(4):
for p in doc.paragraphs:
p.text = p.text.replace(f"({االسمi+1})", group[i] if i < len(group) else "")
doc.save("output.docx")
=========================
📄 python-docx (Word) Examples
=========================
doc = Document("template.docx")
doc.save("output.docx")
p = doc.add_paragraph()
run = p.add_run("Formatted Text")
run.bold = True
run.font.size = Pt(14)
=========================
🔁 SPLIT DOCUMENTS IN CHUNKS and replace names
=========================
# Save result
doc.save("output.docx")
=========================
🔁 SPLIT DOCUMENTS IN CHUNKS
=========================
for i in range(0, len(df), 4):
doc = Document("template.docx")
group = df.iloc[i:i+4]["]"االسم.tolist()
for j in range(4):
for p in doc.paragraphs:
p.text = p.text.replace(f"({االسمj+1})", group[j] if j < len(group) else
"")
doc.save(f"output_{i//4 + 1}.docx")
=========================
📊 pandas + openpyxl (Excel) Examples
=========================
df = pd.read_excel("data.xlsx")
df.to_excel("new_data.xlsx", index=False)
earliest_date = df.groupby("]"التاريخ"[)"الوظيفة.min()
print(earliest_date)
Excel (students.xlsx):
------------------------
| االسم |
|----------|
| أحمد |
| منى |
| يوسف |
Python Code:
------------------------------------------
import pandas as pd
from docx import Document
df = pd.read_excel("students.xlsx")
for p in doc.paragraphs:
if "( ")االسمin p.text:
p.text = p.text.replace("(")االسم, name)
doc.save(f"Certificate_{name}.docx")
=========================
📘 Project 2: Staff Report Generator (Moderate)
=========================
Goal: Read employee data from Excel and generate a report table in a Word document.
Excel (employees.xlsx):
------------------------
| | التاريخ | الوظيفة االسم |
|----------|------------|----------------|
| 06-05-2025 | | مهندس نظم عمر |
| 07-05-2025 | | محلل بيانات خالد |
Python Code:
------------------------------------------
import pandas as pd
from docx import Document
df = pd.read_excel("employees.xlsx")
doc = Document()
doc.add_heading("Employee Daily Report", level=1)
doc.save("Staff_Report.docx")
=========================
📘 Project 3: Multi-Page Offer Letters (Advanced)
=========================
Goal: Read job offers from Excel and generate a multi-paragraph Word document for
each candidate.
Excel (offers.xlsx):
------------------------
| | تاريخ البدء | المسمى الوظيفي | الراتب | االسم
|----------|----------------|----------|-------------|
| 01-07-2025 | ج8000 | | مطور برمجيات | ندى
We are pleased to offer you the position of ( )المسمى الوظيفيat our company.
Your starting salary will be ()الراتب, beginning on ()تاريخ البدء.
Best regards,
HR Department
Python Code:
------------------------------------------
import pandas as pd
from docx import Document
df = pd.read_excel("offers.xlsx")
for p in doc.paragraphs:
for key, val in replacements.items():
if key in p.text:
p.text = p.text.replace(key, val)
doc.save(f"Offer_Letter_{row['}]'االسم.docx")
=========================
➜Project 4: Student Evaluation Generator (Excel ➜ Word & Feedback in Excel)
=========================
Goal:
- Read student scores from Excel
- Generate personalized Word feedback letters
- Write feedback evaluations back to Excel
Excel (students_scores.xlsx):
------------------------
| | الدرجة | االسم
|--------|--------|
| 90 | خالد |
| 72 | منى |
| 55 | أحمد |
Python Code:
------------------------------------------
import pandas as pd
from docx import Document
df = pd.read_excel("students_scores.xlsx")
def get_evaluation(score):
if score >= 85:
return ""ممتاز
elif score >= 70:
return ""جيد جدًا
elif score >= 50:
return ""مقبول
else:
return ""ضعيف
doc = Document("feedback_template.docx")
for p in doc.paragraphs:
p.text = p.text.replace("(")االسم, name)
p.text = p.text.replace("(")الدرجة, str(score))
p.text = p.text.replace("(")التقييم, evaluation)
doc.save(f"Feedback_{name}.docx")
df.to_excel("students_scores_updated.xlsx", index=False)
=========================
📎 TIPS & TRICKS
=========================
- Always check encoding if you read/write Arabic data.
- Excel date columns can be converted to strings using: df["date"] =
df["date"].astype(str)
- python-docx does not support editing headers/footers directly.
=========================
📂 FILE FORMATS SUPPORTED
=========================
- .docx for Word files (not .doc)
- .xlsx for Excel files (not .xls)