简体   繁体   中英

Export database to Excel using Java

I am using Java and APACHE POI. I tried to solve by creating different rows. It did not work. Any suggestions or alternative way?

 int rowCount01 = 1;
 int rowCount02 = 1;
  if (action.equalsIgnoreCase("ANIMAL")) {
                      Row row01 = sheet02.createRow(rowCount01++);
                      Cell cell = row01.createCell(0);
                      cell.setCellValue(resourceName); 
                  }else {
                      Row row02 = sheet02.createRow(rowCount02++);
                      Cell cell = row02.createCell(1);
                      cell.setCellValue(resourceName); 
                  }

I have a database:

Resource Action
Apple fruits
Cat animal
Banana fruits
Dog animal
Lion animal

Now using Apache POI, I need to export it in excel file in this way:

Animal Fruits
Cat Apple
Dog Banana
Lion

you can make use of a simple lib called jxls ( http://jxls.sourceforge.net/ ) to first all create a template like what you want and then provide the data to fill your template.

here is a good example from their website

logger.info("Running Object Collection demo");
    List<Employee> employees = generateSampleEmployeeData();
    try(InputStream is = ObjectCollectionDemo.class.getResourceAsStream("object_collection_template.xls")) {
        try (OutputStream os = new FileOutputStream("target/object_collection_output.xls")) {
            Context context = new Context();
            context.putVar("employees", employees);
            JxlsHelper.getInstance().processTemplate(is, os, context);
        }
    }

You could try using a HashMap<String, String> to connect two specific parameters. An alternative way would be to implement it in a Object oriented way or using the JSON format.

After implementing one of the ways above, you could perform actions on the given elements (in a list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM