Hello everyone,
In the good spirit of sharing knowledge , here are the Cypthon and Ironpython version of a simple script I made to test the excel reading application.
I think they are easiest to read/understand and directly use the excel api so there are plenty of possibilities to extend. That’s the idea in my head right now … will find out if it is true
!
One thing I did find with the Cpython version is that excel opens slower and this seems to cause a crash in the script because it cannot read out immediately. Any ideas on how to prevent this?
Cpython:
#! python3
# -*- coding: utf-8 -*-
import clr
import System
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import OpenFileDialog
clr.AddReference('Microsoft.Office.Interop.Excel')
from Microsoft.Office.Interop import Excel
def open_excel_file():
# Create Excel application object
excel_app = Excel.ApplicationClass()
excel_app.Visible = True
# Create an open file dialog
dialog = OpenFileDialog()
dialog.Filter = 'Excel Files|*.xlsx'
# Show the dialog and get the selected file
result = dialog.ShowDialog()
if result == System.Windows.Forms.DialogResult.OK:
filename = dialog.FileName
# Open the selected Excel workbook
workbook = excel_app.Workbooks.Open(filename)
# For example, print the value of cell A1 in the first worksheet:
worksheet = workbook.Worksheets[1]
cell = worksheet.Range["A1"]
print(cell.Value2)
# Don't forget to clean up when you're done:
workbook.Close()
excel_app.Quit()
open_excel_file()
Ironpython:
# -*- coding: utf-8 -*-
import clr
import System
clr.AddReference('Microsoft.Office.Interop.Excel')
from Microsoft.Office.Interop import Excel
from pyrevit import forms
def open_excel_file():
# Create Excel application object
excel_app = Excel.ApplicationClass()
excel_app.Visible = True
filename = forms.pick_excel_file()
# Open the selected Excel workbook
workbook = excel_app.Workbooks.Open(filename)
# For example, print the value of cell A1 in the first worksheet:
worksheet = workbook.Worksheets[1]
cell = worksheet.Range["A1"]
print(cell.Value2)
# Don't forget to clean up when you're done:
workbook.Close()
excel_app.Quit()
open_excel_file()