This article will introduce how to convert Excel to Image using Java codes with the help of a free third-party library called Free Spire.XLS for Java. The library supports converting a whole worksheet to Image, and also can convert a specific range of cells in a worksheet to Image. Besides, when converting Excel to Image, it supports setting dpi value of the image. The following code samples will separately demonstrate the functions above.
BEFORE RUNNING CODES
First of all, we need to create a
development environment to run Java codes. Download and install JDK and
Intellij IDEA, and then add a Jar file called Spire.Xls.jar which can be found
in the “lib” folder of the Free Spire.XLS for Java library to IDEA. Or you can
reference it by using the following Maven configurations.
USING THE CODE
Next, let’s find the
corresponding code samples. The following is the screenshot of my Excel sample.
l Convert a
whole worksheet to Image
import com.spire.xls.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ToImage {
public static void main(String[] args) throws IOException {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Save the sheet to image
BufferedImage bufferedImage = sheet.toImage(sheet.getFirstRow(), sheet.getFirstColumn(), sheet.getLastRow(), sheet.getLastColumn());
ImageIO.write(bufferedImage,"PNG",new File("output/ToImage.png"));
}
}
Output
l Convert a specific range of cells to Imageimport com.spire.xls.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class SpecificCellsToImage {
public static void main(String[] args) throws IOException {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Specify Cell Ranges and save to image formats
BufferedImage bufferedImage = sheet.toImage(1, 1, 5, 4);
ImageIO.write(bufferedImage,"PNG",new File("output/specificCellsToImage.png"));
}
}Output
l Set Dpi when converting Excel to Imageimport com.spire.xls.*;
public class SetDpiToImage {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an Excel file
wb.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");
//Set dpi on x and y axis
wb.getConverterSetting().setXDpi(400);
wb.getConverterSetting().setYDpi(400);
//Declare a Worksheet variable
Worksheet sheet;
//Loop through the worksheets
for (int i = 0; i < wb.getWorksheets().size(); i++) {
//Get the specific worksheet
sheet = wb.getWorksheets().get(i);
//Convert worksheet to image
sheet.saveToImage("output/image-" + i + ".png");
}
}
}
No comments:
Post a Comment