1

I want to extract/read a chart (Bar graph/ Pie chart etc.) from my .xlsx file using Apache POI and Java and save it as an image or as a PDF on my hard drive.

Is this possible? If yes, how?

Thank you!

Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62
  • Possible duplicate of [How do I export charts from Excel as graphics](http://stackoverflow.com/questions/2495480/how-do-i-export-charts-from-excel-as-graphics) – Draken Apr 25 '16 at 07:53
  • I do not want to use Aspose as it is not free. About JExcel, I can see it is not recommended to use instead of Apache POI. – Akshay Lokur Apr 25 '16 at 09:19

1 Answers1

2

After much investigation, apparently I can see that it is not possible to extract charts from Excel using Apache POI and save it as an image or as a PDF.

The approach one can take in this situation is to use COM based solution using Com4j (http://com4j.kohsuke.org/) to convert Excel to PDF and then use Apache PDFBox (https://pdfbox.apache.org/) to convert from PDF to Image.


Giving below brief details about how to use Com4j to convert Excel into PDF programmatically:

  1. Generate Java classes artifacts from Excel with following command:

    java -jar tlbimp-2.1.jar -o wsh -p com.mycompany.excel4j "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.exe"

    We need 3 JARs for above conversion: com4j-2.1.jar, tlbimp-2.1.jar, args4j-2.0.8.jar

    We may download corresponding JARs from - http://com4j.kohsuke.org/maven-com4j-plugin/dependencies.html

    For more information, refer: http://com4j.kohsuke.org/

  2. Copy generated Java artifacts into your workspace or create a JAR of these and use after adding it into application classpath.

  3. Use following snippet to invoke generated COM APIs from Java and convert first sheet of specified Excel file to PDF (Replace accordingly on your computer the paths mentioned in the following snippet for Excel and PDF files):

    public static void main(String[] args) throws Exception {
        _Application excelApplication = ClassFactory.createApplication();
    
    _Workbook workbook = excelApplication
            .workbooks()
            .open("C:\\Users\\Akki\\Desktop\\MyExcel.xlsx",
                    null, null, null, null,
                    null, null, null,
                    null, null, null, null, null,
                    null, null, 0);
    
    workbook.exportAsFixedFormat(XlFixedFormatType.xlTypePDF, "C:\\Users\\Akki\\Desktop\\MyPDF.pdf", null, null, null, null, null, null, null);
    
    workbook.close(false, null,null, 0);
    
    excelApplication.quit();
    
    System.out.println("Converted Excel to PDF!"); }
    

Cheers,

Akshay

Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62