समझिए
ज़रूरत: Windows या Mac पर इंस्टॉल Excel, और pip install xlwings। यह सर्वर या GitHub Actions पर नहीं चलेगा — वहाँ pandas + openpyxl इस्तेमाल करें।
1. वर्कबुक से जुड़ें
import xlwings as xw
wb = xw.Book("sales.xlsx") # opens the file in Excel (or connects if already open)
# wb = xw.books.active # the workbook currently in front
sht = wb.sheets["Data"]
आप Excel खुलता देखेंगे और स्क्रिप्ट चलते-चलते बदलाव लाइव दिखेंगे।
2. सेल पढ़ें और लिखें
print(sht["A1"].value) # single value
sht["G1"].value = "Checked by Python"
values = sht["A2:E5"].value # list of lists
sht["A10"].value = [["Product", "Qty"], ["Laptop", 12]] # writes a 2×2 block
3. पूरी टेबल ↔ pandas
import pandas as pd
df = sht["A1"].options(pd.DataFrame, index=False, expand="table").value
summary = df.groupby("Region", as_index=False)["Amount"].sum()
sht["H1"].options(index=False).value = summary
expand="table" A1 से डेटा के पूरे ब्लॉक तक फैलता है, Ctrl + A की तरह। xlwings इस्तेमाल करने की यही मुख्य वजह है: यूज़र का मौजूदा डेटा उठाओ, pandas का जादू करो, नतीजा वापस रखो।
4. फ़ॉर्मेटिंग और मददगार चीज़ें
sht["H1:I1"].font.bold = True
sht["H1:I1"].color = (31, 78, 120) # fill colour as RGB
sht["H1:I1"].font.color = (255, 255, 255)
sht.autofit() # real Excel AutoFit
last_row = sht["A1"].end("down").row # like Ctrl + ↓
wb.save()
5. Python से VBA मैक्रो चलाएँ
format_header = wb.macro("FormatHeader") # a macro in this .xlsm
format_header()
जब टीम के पास पहले से मैक्रो हों तब काम का — Python डेटा संभाले, VBA वह करे जिसमें वह पहले से अच्छा है।
6. Excel को बैकग्राउंड में चलाएँ
with xw.App(visible=False) as app:
wb = app.books.open("sales.xlsx")
wb.sheets["Data"]["G1"].value = "Updated"
wb.save()
wb.close()
Excel छिपकर शुरू होता है, काम करता है और बंद हो जाता है — अपने PC पर शेड्यूल जॉब के लिए काम का (PC लॉग-इन होना चाहिए)।
7. Excel के बटन से Python चलाएँ
- ऐड-इन एक बार इंस्टॉल करें:
xlwings addin install - प्रोजेक्ट बनाएँ:
xlwings quickstart salestool— इससे उसी फ़ोल्डर मेंsalestool.xlsmऔरsalestool.pyबनते हैं। salestool.pyमें:
import xlwings as xw
import pandas as pd
def main():
wb = xw.Book.caller() # the workbook that clicked the button
sht = wb.sheets["Data"]
df = sht["A1"].options(pd.DataFrame, index=False, expand="table").value
out = df.groupby("Region", as_index=False)["Amount"].sum()
wb.sheets["Summary"]["A1"].options(index=False).value = out
salestool.xlsmके VBA मॉड्यूल में पहले सेRunPython "import salestool; salestool.main()"जैसी कॉल होती है। उस मैक्रो को बटन से जोड़ें।
अब यूज़र Excel में बटन दबाते हैं और काम Python करता है। (Windows पर xlwings @xw.func से Python फ़ंक्शन को वर्कशीट फ़ॉर्मूला भी बना सकता है।)
8. लाइसेंस की बात
xlwings खुद ओपन-सोर्स और मुफ़्त है। कुछ अतिरिक्त फ़ीचर पेड "xlwings PRO" का हिस्सा हैं — इस लेसन का सब कुछ मुफ़्त वर्ज़न में चलता है।
आम गलतियाँ
सर्वर पर शेड्यूल जॉब में xlwings इस्तेमाल करना (वहाँ Excel नहीं)। expand="table" भूलकर एक ही वैल्यू पाना। स्क्रिप्ट क्रैश होने पर छिपे Excel चलते छोड़ देना — with xw.App() वाला रूप इस्तेमाल करें।