I want to create excel files in Groovy, then have them plotted. This code was taken from an example using Microsoft's Shell Scripting language:
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1,1) = "Operating System"
objWorksheet.Cells(2,1) = "Windows Server 2003"
objWorksheet.Cells(3,1) = "Windows XP"
objWorksheet.Cells(5,1) = "Windows NT 4.0"
objWorksheet.Cells(6,1) = "Other"
objWorksheet.Cells(1,2) = "Number of Computers"
objWorksheet.Cells(2,2) = 145
objWorksheet.Cells(3,2) = 987
objWorksheet.Cells(4,2) = 611
objWorksheet.Cells(5,2) = 41
objWorksheet.Cells(6,2) = 56
Set objRange = objWorksheet.UsedRange
objRange.Select
Set colCharts = objExcel.Charts
colCharts.Add()
Set objChart = colCharts(1)
objChart.Activate
objChart.HasLegend = FALSE
objChart.ChartTitle.Text = "Operating System Use"
How would I modify this to work in Groovy?
You need groovy to work with COM. Towards the bottom of this page is an example of automating Excel.
EDITS
Here's your example translated into Groovy (I ran this under Groovy 1.8.2):
import org.codehaus.groovy.scriptom.*
import org.codehaus.groovy.scriptom.tlb.office.excel.XlChartType
import org.codehaus.groovy.scriptom.tlb.office.excel.XlRowCol
import org.codehaus.groovy.scriptom.tlb.office.excel.XlChartLocation
// create a xls instance
def xls = new ActiveXObject("Excel.Application")
xls.Visible = true
Thread.sleep(1000)
// get the workbooks object
def workbooks = xls.Workbooks
// add a new workbook
def workbook = workbooks.Add()
// select the active sheet
def sheet = workbook.ActiveSheet
cell = sheet.Range("A1")
cell.Value = "Operating System"
cell = sheet.Range("A2")
cell.Value = "Windows Server 2003"
cell = sheet.Range("A3")
cell.Value = "Windows XP"
cell = sheet.Range("A4")
cell.Value = "Windows NT 4.0"
cell = sheet.Range("A5")
cell.Value = "Other"
cell = sheet.Range("B1")
cell.Value = "Number of Computers"
cell = sheet.Range("B2")
cell.Value = 145
cell = sheet.Range("B3")
cell.Value = 987
cell = sheet.Range("B4")
cell.Value = 611
cell = sheet.Range("B5")
cell.Value = 41
def chart = workbook.Charts.Add(Scriptom.MISSING, sheet) // create chart object
chart.ChartType = XlChartType.xl3DArea // set type to pie
chart.SetSourceData(sheet.Range("A1:B5"), XlRowCol.xlColumns) // set source data
chart.Location(XlChartLocation.xlLocationAsNewSheet) // add chart as new sheet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With