I was curious if it was possible to store values into excel spreadsheet cells? And if so, how would one go about completing this? I also have multiple values that I would li
Excel is not a trivial file format to parse and write.
The following example demonstrates how to create a macro that writes an excel file:
<excelWrite file="target/workbook.xlsx" values="Hello,world"/>
The macro uses the Apache POI java library.
Running the build will generate an excel file
├── build.xml
└── target
└── workbook.xlsx
Additional notes:
<project name="demo" default="build" xmlns:ivy="antlib:org.apache.ivy.ant">
<!--
==========
Properties
==========
-->
<property name="build.dir" location="target"/>
<available classname="org.apache.ivy.Main" property="ivy.installed"/>
<!--
======
Macros
======
-->
<macrodef name="excelWrite">
<attribute name="file"/>
<attribute name="values"/>
<attribute name="sheetName" default="ANT demo"/>
<sequential>
<ivy:cachepath pathid="build.path">
<dependency org="org.codehaus.groovy" name="groovy-all" rev="2.2.2" conf="default"/>
<dependency org="org.apache.poi" name="poi-ooxml" rev="3.10-FINAL" conf="default"/>
</ivy:cachepath>
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>
<groovy>
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.ss.usermodel.CreationHelper
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Row
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("@{sheetName}");
CreationHelper helper = wb.getCreationHelper();
// Write data to a single row
short rowpos = 0;
short colpos = 0;
Row row = sheet.createRow(rowpos);
"@{values}".split(",").each {
row.createCell(colpos++).setCellValue(helper.createRichTextString(it));
}
// Ensure parent directory exists
def file = new File("@{file}")
file.getParentFile().mkdirs()
project.log "Writing Excel file: "+file
file.withOutputStream {
wb.write(it)
}
</groovy>
</sequential>
</macrodef>
<!--
=============
Project setup
=============
-->
<target name="install-ivy" description="Install ivy" unless="ivy.installed">
<mkdir dir="${user.home}/.ant/lib"/>
<get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar"/>
<fail message="Ivy has been installed. Run the build again"/>
</target>
<!--
==========
Main logic
==========
-->
<target name="build" depends="install-ivy" description="Create an Excel file">
<excelWrite file="${build.dir}/workbook.xlsx" values="Hello,world"/>
</target>
<!--
===============
Project Cleanup
===============
-->
<target name="clean" description="Cleanup build files">
<delete dir="${build.dir}"/>
</target>
<target name="clean-all" depends="clean" description="Additionally purge ivy cache">
<ivy:cleancache/>
</target>
</project>