This code example shows how to use the
Apache POI library to create an Excel file that contains an image (either a local file, or downloaded from the net).
import java.io.*;
import java.net.URL;
import org.apache.poi.hssf.usermodel.*;
public class CreateExcelWithImage {
public static void main (String[] args) throws IOException {
int colIdx = 1, rowIdx = 1;
URL url = new URL("http://poi.apache.org/resources/images/project-logo.jpg");
InputStream is = url.openStream();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("image");
for (int i=0; i<=rowIdx; i++)
sheet.createRow(i);
sheet.setColumnWidth(colIdx, 5000);
sheet.getRow(rowIdx).setHeightInPoints(100);
ByteArrayOutputStream img_bytes = new ByteArrayOutputStream();
int b;
while ((b = is.read()) != -1)
img_bytes.write(b);
is.close();
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) colIdx, rowIdx,
(short) (colIdx+1), rowIdx+1);
int index = wb.addPicture(img_bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG);
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
patriarch.createPicture(anchor, index);
anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);
FileOutputStream fos = new FileOutputStream("image.xls");
wb.write(fos);
fos.close();
}
}
CategoryCodeSamples CodeBarn