DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Convert Excel to Image in Java

With the help of Spire.XLS for Java, we can easily convert Excel workbook and Excel worksheets to image with high quality in Java applications. In this article, I will explain the solutions of converting the Excel file to bitmap images in PNG, BMP, JPEG etc. And when we convert Excel to Images, we can set the DPI for the image and convert the Excel to image by page breaks.

Converting Excel to Image and set the image DPI. Spire.XLS for Java offers sheet.saveToImage() method to save Excel as image directly. And we could also use sheet.saveToImage (result, firstRow, firstColumn, lastRow, lastColumn); to convert the defined cell range to images.

import com.spire.xls.*;

public class ExceltoImage {
    public static void main(String[] args) {


        //Load the sample document
        Workbook wb = new Workbook();
        wb.loadFromFile("Sample.xlsx");

        //set the image DPI 
        wb.getConverterSetting().setXDpi(200);
        wb.getConverterSetting().setYDpi(200);

        //get the first worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Save to image
        sheet.saveToImage("ExceltoImage.png");

        //save the defined cell range to image
        sheet.saveToImage("CellrangesToImg.png",5,1,14,4);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Convert the Excel to Images by page breaks. When we deal with the Excel with a large of data, we will add the page breaks to the Excel file to ensure it can be printed and converted correctly. Spire.XLS for java supports to convert Excel to images by page breaks.

import com.spire.xls.*;

import java.util.List;
import java.util.Map;

public class ExceltoImagebyPagebreaks {
    public static void main(String[] args) throws Exception {


        //Load the sample document
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");
        int count = 1;

        //get the page split info.
        List<Map<Integer, PageColRow>> pageInfoList = workbook.getSplitPageInfo();


        //Convert to images by pagebreaks
        for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
           Worksheet sheet = workbook.getWorksheets().get(i);
            Map<Integer, PageColRow> integerPageColRowMap = pageInfoList.get(i);
            for (Map.Entry<Integer, PageColRow> entry : integerPageColRowMap.entrySet()) {
                PageColRow colRow = entry.getValue();
                String result=("output/out" + (count++) + ".png");
                sheet.saveToImage (result, colRow.StartRow, colRow.StartCol, colRow.EndRow, colRow.EndCol);
             }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)