PageRenderTime 138ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/ls/upload/ImageToExcel.java

https://github.com/bluecitymoon/littleshop
Java | 91 lines | 62 code | 25 blank | 4 comment | 2 complexity | b56833db7b8492e781ee6d2b2e9e0472 MD5 | raw file
  1. package com.ls.upload;
  2. import java.awt.image.BufferedImage;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import javax.imageio.ImageIO;
  9. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  10. import org.apache.poi.hssf.usermodel.HSSFPatriarch;
  11. import org.apache.poi.hssf.usermodel.HSSFSheet;
  12. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  13. public class ImageToExcel {
  14. private HSSFWorkbook wb = null;
  15. private HSSFSheet sheet = null;
  16. private HSSFPatriarch patriarch = null;
  17. public ImageToExcel() {
  18. wb = new HSSFWorkbook();
  19. sheet = wb.createSheet("mysheets1");
  20. sheet.setDefaultColumnWidth((short) 2);
  21. patriarch = sheet.createDrawingPatriarch();
  22. }
  23. // 这个是从网上找到的方法
  24. private void setImageToCell(short col1, int row1, short col2, int row2, String imagePath) {
  25. BufferedImage bufferImg = null;
  26. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  27. try {
  28. bufferImg = ImageIO.read(new File(imagePath));
  29. ImageIO.write(bufferImg, "jpg", byteArrayOut);
  30. // 能否写多张图片,关键在与HSSFPatriarch patriarch 这个变量。写多张图片时,
  31. // HSSFPatriarch patriarch 应该时一个对象,不应该每次多新创建对象。
  32. // HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  33. HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, col1, row1, col2, row2);
  34. anchor.setAnchorType(2);
  35. patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. public void createExcel() {
  41. FileOutputStream fileOut = null;
  42. try {
  43. setImageToCell((short) 1, 1, (short) 8, 6, "D://20140703100023310.jpg");
  44. setImageToCell((short) 1, 8, (short) 8, 13, "D://20140703100020943.jpg");
  45. setImageToCell((short) 1, 15, (short) 8, 20, "D://20140703100018827.jpg");
  46. fileOut = new FileOutputStream("D:\\test.xlsx");
  47. wb.write(fileOut);
  48. } catch (FileNotFoundException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. if (fileOut != null) {
  54. try {
  55. fileOut.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. }
  62. public static void main(String[] args) {
  63. ImageToExcel excel = new ImageToExcel();
  64. excel.createExcel();
  65. }
  66. }