本文将介绍如何使用Spire.XLS for Java在Excel文档中插入和提取图片。
插入图片
import com.spire.xls.ExcelPicture;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class InsertImage {
public static void main(String[] args){
//创建Workbook实例
Workbook workbook = new Workbook();
//加载Excel文档
workbook.loadFromFile("Input.xlsx");
//获取第一张工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//添加图片到工作表的指定位置
ExcelPicture pic = sheet.getPictures().add(4, 1,"image.jpg");
//设置图片的宽度和高度
pic.setWidth(500);
pic.setHeight(300);
//保存文档
workbook.saveToFile("InsertImage.xlsx", ExcelVersion.Version2013);
}
}
提取图片
import com.spire.xls.ExcelPicture;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ReadImage {
public static void main(String[] args) throws IOException {
//创建Workbook实例
Workbook workbook = new Workbook();
//加载Excel文档
workbook.loadFromFile("InsertImage.xlsx");
//获取第一张工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//获取工作表中第一张图片并保存到指定路径
ExcelPicture pic = sheet.getPictures().get(0);
BufferedImage loImage = pic.getPicture();
ImageIO.write(loImage,"jpg",new File("output/ReadImage.jpg"));
}
}