Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7701617
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:01:58+00:00 2026-05-31T23:01:58+00:00

I’m new to groovy, and I’ve used the ExcelBuilder code referenced below to iterate

  • 0

I’m new to groovy, and I’ve used the ExcelBuilder code referenced below to iterate through an excel spreadsheet to grab data. Is there an easy to write data as I iterate?

For example, row 1 might have data like this (CSV):

value1,value2

And after I iterate, I want it to look like this:

value1,value2,value3

http://www.technipelago.se/content/technipelago/blog/44

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T23:01:59+00:00Added an answer on May 31, 2026 at 11:01 pm

    Yes, this can be done! As I got into the guts of it, I realized that the problem I was trying to solve wasn’t the same as trying to read and write from the same file at the same time, but rather the excel data was stored in an object that I could freely manipulate whenever I wanted. So I added methods specific to my needs – which may or many not meet the needs of anyone else – and I post them here for smarter people to pick apart. At the end of it all, it is now doing what I want it to do.

    I added a cell method that takes an index (number or label) and a value which will update a cell for the current row in context (specifically while using .eachLine()), and a .putRow() method that adds a whole row to the spreadsheet specified. It also handles Excel 2003, 2007, and 2010 formats. When files, sheets, or cells referenced don’t exist, they get created. Since my source spreadsheets often have formulas and charts ready to display the data I’m entering, the .save() and .saveAs() methods call .evaluateAllFormulaCells() before saving.

    To see the code I started with and examples of how it works, check out this blog entry

    Note that both the .save() and .saveAs() methods reload the workbook from the saved file immediately after saving. This is a workaround to a bug in Apache POI that doesn’t seem to be fixed yet (see Exception when writing to the xlsx document several times using apache poi).

    import groovy.lang.Closure;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Map;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
    
    class Excel
    {
        def workbook;
        def sheet;
        def labels;
        def row;
        def infilename;
        def outfilename;
    
        Excel(String fileName)
        {
            HSSFRow.metaClass.getAt = {int index ->
                def cell = delegate.getCell(index);
                if(! cell)
                {
                    return null;
                }
    
                def value;
    
                switch (cell.cellType)
                {
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        if(HSSFDateUtil.isCellDateFormatted(cell))
                        {
                            value = cell.dateCellValue;
                        }
                        else
                        {
                            value = new DataFormatter().formatCellValue(cell);
                        }
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        value = cell.booleanCellValue
                        break;
                    default:
                        value = new DataFormatter().formatCellValue(cell);
                        break;
                }
    
                return value
            }
    
            XSSFRow.metaClass.getAt = {int index ->
                def cell = delegate.getCell(index);
                if(! cell)
                {
                    return null;
                }
                def value = new DataFormatter().formatCellValue(cell);
    
                switch (cell.cellType)
                {
                    case XSSFCell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell))
                        {
                            value = cell.dateCellValue;
                        }
                        else
                        {
                            value = new DataFormatter().formatCellValue(cell);
                        }
                        break;
                    case XSSFCell.CELL_TYPE_BOOLEAN:
                        value = cell.booleanCellValue
                        break;
                    default:
                        value = new DataFormatter().formatCellValue(cell);
                        break;
                }
    
                return value;
            }
    
            infilename = fileName;
            outfilename = fileName;
    
            try
            {
                workbook = WorkbookFactory.create(new FileInputStream(infilename));
            }
            catch (FileNotFoundException e)
            {
                workbook = (infilename =~ /(?is:\.xlsx)$/) ?  new XSSFWorkbook() : new HSSFWorkbook();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    
        def getSheet(index)
        {
            def requested_sheet;
    
            if(!index) index = 0;
    
            if(index instanceof Number)
            {
                requested_sheet = (workbook.getNumberOfSheets >= index) ? workbook.getSheetAt(index) : workbook.createSheet();
            }
            else if (index ==~ /^\d+$/)
            {
                requested_sheet = (workbook.getNumberOfSheets >= Integer.valueOf(index)) ? workbook.getSheetAt(Integer.valueOf(index)) : workbook.createSheet();
            }
            else
            {
                requested_sheet = (workbook.getSheetIndex(index) > -1) ? workbook.getSheet(index) : workbook.createSheet(index);
            }
    
            return requested_sheet;
        }
    
        def cell(index)
        {
            if (labels && (index instanceof String))
            {
                index = labels.indexOf(index.toLowerCase());
            }
    
            if (row[index] == null)
            {
                row.createCell(index);
            }
    
            return row[index];
        }
    
        def cell(index, value)
        {
            if (labels.indexOf(index.toLowerCase()) == -1)
            {
                labels.push(index.toLowerCase());
    
                def frow  = sheet.getRow(0);
                def ncell = frow.createCell(labels.indexOf(index.toLowerCase()));
                ncell.setCellValue(index.toString());
            }
    
            def cell = (labels && (index instanceof String)) ? row.getCell(labels.indexOf(index.toLowerCase())) : row.getCell(index);
    
            if (cell == null)
            {
                cell = (index instanceof String) ? row.createCell(labels.indexOf(index.toLowerCase())) : row.createCell(index);
            }
    
            cell.setCellValue(value);
        }
    
        def putRow (sheetName, Map values = [:])
        {
            def requested_sheet = getSheet(sheetName);
            if (requested_sheet)
            {
                def lrow;
                if (requested_sheet.getPhysicalNumberOfRows() == 0)
                {
                    lrow = requested_sheet.createRow(0);
                    def lcounter = 0;
                    values.each {entry->
                        def lcell = lrow.createCell(lcounter);
                        lcell.setCellValue(entry.key);
                        lcounter++;
                    }
                }
                else
                {
                    lrow = requested_sheet.getRow(0);
                }
    
                def sheetLabels = lrow.collect{it.toString().toLowerCase()}
                def vrow = requested_sheet.createRow(requested_sheet.getLastRowNum() + 1);
                values.each {entry->
                    def vcell = vrow.createCell(sheetLabels.indexOf(entry.key.toLowerCase()));
                    vcell.setCellValue(entry.value);
                }
            }
        }
    
        def propertyMissing(String name)
        {
            cell(name);
        }
    
        def propertyMissing(String name, value)
        {
            cell(name, value);
        }
    
        def eachLine (Map params = [:], Closure closure)
        {
            /*
             * Parameters:
             * skiprows    : The number of rows to skip before the first line of data and/or labels
             * offset      : The number of rows to skip (after labels) before returning rows
             * max         : The maximum number of rows to iterate
             * sheet       : The name (string) or index (integer) of the worksheet to use
             * labels      : A boolean to treat the first row as a header row (data can be reference by label)
             *
             */
            def skiprows = params.skiprows ?: 0;
            def offset = params.offset ?: 0;
            def max = params.max ?: 9999999;
            sheet = getSheet(params.sheet);
            def rowIterator = sheet.rowIterator();
            def linesRead = 0;
    
            skiprows.times{ rowIterator.next() }
    
            if(params.labels)
            {
                labels = rowIterator.next().collect{it.toString().toLowerCase()}
            }
    
            offset.times{ rowIterator.next() }
    
            closure.setDelegate(this);
    
            while(rowIterator.hasNext() && linesRead++ < max)
            {
                row = rowIterator.next();
                closure.call(row);
            }
        }
    
        def save ()
        {
            if (workbook.getClass().toString().indexOf("XSSF") > -1)
            {
                XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
            }
            else
            {
                HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
            }
    
            if (outfilename != null)
            {
                try
                {
                    FileOutputStream output = new FileOutputStream(outfilename);
                    workbook.write(output);
                    output.close();
    
                    workbook = null;
                    workbook = WorkbookFactory.create(new FileInputStream(outfilename));
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    
        def saveAs (String fileName)
        {
            if (workbook.getClass().toString().indexOf("XSSF") > -1)
            {
                XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
            }
            else
            {
                HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
            }
    
            try
            {
                FileOutputStream output = new FileOutputStream(fileName);
                workbook.write(output);
                output.close();
                outfilename = fileName;
    
                workbook = null;
                workbook = WorkbookFactory.create(new FileInputStream(outfilename));
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    

    If you see any glaring errors or ways to improve (other than style), I’d love to hear them. Again, Groovy is not a language I have much experience with, and I haven’t done anything with Java in several years, so I’m sure there might be some better ways to do things.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Does anyone know how can I replace this 2 symbol below from the string
I want to construct a data frame in an Rcpp function, but when I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.