Java: How to write data in Excel file using Apache POI

Last updated on:

In my current project I'm storing value in a property file, then getting it and parsing to the Excel file, which later on I will need to upload to the software. I'm using Apache POI - the Java API for Microsoft Documents. Here is how you do it:

 public static void writeExcel() {

        String c_code = getDataValue("cCode");
        //Blank workbook
        System.out.println("Here is what we got: " + c_code);
        XSSFWorkbook workbook = new XSSFWorkbook();
        //Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Test Data");
        // shadeAlt(sheet);
        //This data needs to be written (Object[])
        Map<String, Object[]> data = new TreeMap<String, Object[]>();
        data.put("1", new Object[]{"1", "110808", "26", "0", "123456789", "90", c_code, "Mia Hernandez", "C01", "CorrectionInfo", c_code});

        //Iterate over data and write to sheet
        Set<String> keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset)
        {
            Row row = sheet.createRow(rownum++);
            Object [] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr)
            {
                Cell cell = row.createCell(cellnum++);
                if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        try
        {
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("test_c_code.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("etest_c_code.xlsx written successfully.");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

I use maven dependency in order to get library to my project:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.