热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

利用POI从Excel取图,自动制作PPT

Excel中的模版是这样的一个PNG或者jpg另外有一段表格如图首先呢,我们会想到poi这个工具然后我的思路是先把图片取出来,然后利用G2P将表格画出

Excel中的模版是这样的 一个PNG 或者jpg 另外有一段表格 如图

首先呢,我们会想到poi这个工具

然后我的思路是先把图片取出来,然后利用G2P 将表格画出来,这样一想,就很简单了。下面看代码

取表格 

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;import javax.imageio.ImageIO;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import sun.awt.SunHints;public class DrawFromExcel {public static void main(String[] args) {}public static void ImgUtile(String file,int from,int from1,int to,int to1) throws Exception {// 给定两个初始值,标志出导出区域,两个行列组合的单元格int[] fromIndex = {from,from1};int[] toIndex = {to,to1};int imageWidth = 0;//图片初始长度值int imageHeight =0;//初始宽带值Workbook wb = WorkbookFactory.create(new FileInputStream(file));//打开路径 (名字可动态传值方便)Sheet sheet = wb.getSheetAt(0);List rangeAddress = sheet.getMergedRegions(); // 获取整个sheet中合并单元格组合的集合// 首先做初步的边界检测,如果指定区域是不合法的则抛出异常int rowSum = sheet.getPhysicalNumberOfRows();int colSum = sheet.getRow(0).getPhysicalNumberOfCells();if (fromIndex[0] > rowSum || fromIndex[0] > toIndex[0] || toIndex[0] > rowSum) {throw new Exception("the rowIndex of the area is wrong!");}if (fromIndex[1] > colSum || fromIndex[1] > toIndex[1] || toIndex[1] > colSum) {throw new Exception("the colIndex of the area is wrong!");}// 计算实际需要载入内存的二维Cell数组的大小,剔除隐藏行列int rowSize = toIndex[0]-fromIndex[0];//区域划分行System.out.println("rowSize:"+rowSize);int colSize = toIndex[1]-fromIndex[1];//区域划分列System.out.println("colSize:"+colSize);// 遍历需要扫描的区域UserCell[][] cells = new UserCell[rowSize][colSize];int[] rowPixPos = new int[rowSize + 1];rowPixPos[0] = 0;int[] colPixPos = new int[colSize + 1];colPixPos[0] = 0;for (int i = fromIndex[0]; i =fromIndex[0]) && (j>=fromIndex[1]); //首先行列要在指定区域之间ifShow=ifShow && !(sheet.isColumnHidden(j) || sheet.getRow(i).getZeroHeight()); //其次行列不可以隐藏cells[i-fromIndex[0]][j-fromIndex[1]].setShow(ifShow);// 计算所求区域宽度float widthPix = !ifShow ? 0 : sheet.getColumnWidthInPixels(j); // 如果该单元格是隐藏的,则置宽度为0if (i == fromIndex[0]) {imageWidth += widthPix;}colPixPos[j-fromIndex[1]+1] = (int) (widthPix * 1.15 + colPixPos[j-fromIndex[1]]);}// 计算所求区域高度boolean ifShow=(i>=fromIndex[0]); //行序列在指定区域中间ifShow=ifShow && !sheet.getRow(i).getZeroHeight(); //行序列不能隐藏float heightPoint = !ifShow ? 0 : sheet.getRow(i).getHeightInPoints(); // 如果该单元格是隐藏的,则置高度为0imageHeight += heightPoint; rowPixPos[i-fromIndex[0]+1] = (int) (heightPoint * 96 / 72) + rowPixPos[i-fromIndex[0]];}imageHeight = imageHeight * 96 / 72;imageWidth = imageWidth * 115 / 100;wb.close();List grids = new ArrayList();for (int i = 0; i rowSize-1?rowSize-1:isInMergedStatus[0];int lastColPos=isInMergedStatus[1]>colSize-1?colSize-1:isInMergedStatus[1]; grid.setWidth(colPixPos[lastColPos + 1] - colPixPos[j]);grid.setHeight(rowPixPos[lastRowPos + 1] - rowPixPos[i]);}CellStyle cs =cells[i][j].getCell().getCellStyle();// 单元格背景颜色if (cs.getFillPatternEnum() == FillPatternType.SOLID_FOREGROUND)grid.setBgColor(cells[i][j].getCell().getCellStyle().getFillForegroundColorColor());// 设置字体org.apache.poi.ss.usermodel.Font fOnt= wb.getFontAt(cs.getFontIndex());grid.setFont(font);// 设置字体前景色if (font instanceof XSSFFont) {XSSFFont xf = (XSSFFont) font;grid.setFtColor(xf.getXSSFColor());}// 设置文本String strCell = "";switch (cells[i][j].getCell().getCellType()) {case HSSFCell.CELL_TYPE_NUMERIC: strCell = String.format("%.2f", Double.parseDouble(String.valueOf(cells[i][j].getCell().getNumericCellValue())));break;case HSSFCell.CELL_TYPE_STRING: strCell = cells[i][j].getCell().getStringCellValue();break;case HSSFCell.CELL_TYPE_BOOLEAN:strCell = String.valueOf(cells[i][j].getCell().getBooleanCellValue());break;case HSSFCell.CELL_TYPE_FORMULA:try {strCell = String.valueOf(cells[i][j].getCell().getNumericCellValue());} catch (IllegalStateException e) {strCell = String.valueOf(cells[i][j].getCell().getRichStringCellValue());}break;default:strCell = "";}if(cells[i][j].getCell().getCellStyle().getDataFormatString().contains("0.00%")){try{double dbCell=Double.valueOf(strCell);strCell=new DecimalFormat("#.00").format(dbCell*100)+"%";}catch(NumberFormatException e){} }grid.setText(strCell.matches("\\w*\\.0") ? strCell.substring(0, strCell.length() - 2) : strCell);grids.add(grid);}}BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = image.createGraphics();// 平滑字体g2d.setRenderingHint(SunHints.KEY_ANTIALIASING, SunHints.VALUE_ANTIALIAS_OFF);g2d.setRenderingHint(SunHints.KEY_TEXT_ANTIALIASING, SunHints.VALUE_TEXT_ANTIALIAS_DEFAULT);g2d.setRenderingHint(SunHints.KEY_STROKE_CONTROL, SunHints.VALUE_STROKE_DEFAULT);g2d.setRenderingHint(SunHints.KEY_TEXT_ANTIALIAS_LCD_CONTRAST, 140);g2d.setRenderingHint(SunHints.KEY_FRACTIONALMETRICS, SunHints.VALUE_FRACTIONALMETRICS_OFF);g2d.setRenderingHint(SunHints.KEY_RENDERING, SunHints.VALUE_RENDER_DEFAULT);g2d.setColor(Color.white);g2d.fillRect(0, 0, imageWidth, imageHeight);// 绘制表格for (Grid g : grids) {if (!g.isShow())continue;// 绘制背景色g2d.setColor(g.getBgColor() == null ? Color.white : g.getBgColor());g2d.fillRect(g.getX(), g.getY(), g.getWidth(), g.getHeight());// 绘制边框g2d.setColor(Color.black);g2d.setStroke(new BasicStroke(1));g2d.drawRect(g.getX(), g.getY(), g.getWidth(), g.getHeight());// 绘制文字,居中显示g2d.setColor(g.getFtColor());Font fOnt= g.getFont();FontMetrics fm = g2d.getFontMetrics(font);int strWidth = fm.stringWidth(g.getText());// 获取将要绘制的文字宽度g2d.setFont(font);g2d.drawString(g.getText(),g.getX() + (g.getWidth() - strWidth) / 2,g.getY() + (g.getHeight() - font.getSize()) / 2 + font.getSize());}g2d.dispose();ImageIO.write(image, "png", new File("D:/ddd/testBDg.png"));System.out.println("Output to PNG file Success!");}/*** 判断Excel中的单元格是否为合并单元格* * @param row* @param col* @param rangeAddress* @return 如果不是合并单元格返回{-1,-1},如果是合并单元格并且是一个单元格返回{lastRow,lastCol},* 如果是合并单元格并且不是第一个格子返回{0,0}*/private static int[] isInMerged(int row, int col, List rangeAddress) {int[] isInMergedStatus = { -1, -1 };for (CellRangeAddress cra : rangeAddress) {if (row == cra.getFirstRow() && col == cra.getFirstColumn()) {isInMergedStatus[0] = cra.getLastRow();isInMergedStatus[1] = cra.getLastColumn();return isInMergedStatus;}if (row >= cra.getFirstRow() && row <= cra.getLastRow()) {if (col >= cra.getFirstColumn() && col <= cra.getLastColumn()) {isInMergedStatus[0] = 0;isInMergedStatus[1] = 0;return isInMergedStatus;}}}return isInMergedStatus;}}

取png 

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;/*** @auth zwx* @desciption 利用poi 读取 写出图片操作。* @Date 16:33 2018/12/4*/
public class PoiExercise {public static void main(String[] args) throws Exception {PngUtile("D:/ddd/text3.xlsx","hellow","D:/ddd/");}public static void PngUtile(String FilePath,String newFileName,String ImgFilePath)throws Exception {// 创建文件File file = new File(FilePath);// 创建流InputStream input = new FileInputStream(file);// 获取文件后缀名String fileExt = file.getName().substring(file.getName().lastIndexOf(".") + 1);// 创建WorkbookWorkbook wb = null;// 创建sheetSheet sheet = null;// 根据后缀判断03,07if (fileExt.equals("xls")) {wb = (HSSFWorkbook) WorkbookFactory.create(input);} else {wb = new XSSFWorkbook(input);}// 获取excel sheet总数int sheetNumbers = wb.getNumberOfSheets();// sheet listList> sheetList = new ArrayList>();if (fileExt.equals("xls")) {// 循环sheetfor (int i = 0; i sheetIndexPicMap = null;sheetIndexPicMap = getSheetPictrues03(i, (HSSFSheet) sheet,(HSSFWorkbook) wb);// 将当前sheet图片map存入listsheetList.add(sheetIndexPicMap);}// printImg(sheetList, "d:/saveFile/pic/");} else {getSheetPic07(ImgFilePath, (XSSFSheet) sheet,(XSSFWorkbook) wb,newFileName);}}public static Map getSheetPictrues03(int sheetNum,HSSFSheet sheet, HSSFWorkbook workbook) {Map sheetIndexPicMap = new HashMap();List pictures = workbook.getAllPictures();if (pictures.size() != 0) {HSSFPatriarch hssPatriarch = sheet.getDrawingPatriarch();if (hssPatriarch != null) {for (HSSFShape shape : hssPatriarch.getChildren()) {HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();if (shape instanceof HSSFPicture) {HSSFPicture pic = (HSSFPicture) shape;int pictureIndex = pic.getPictureIndex() - 1;HSSFPictureData picData = pictures.get(pictureIndex);//行列下标都是从0开始的,//这里行数加+1,第一张图片信息行数不准确,测试下就知道了String picIndex = "sheet" + String.valueOf(sheetNum)+ "_[" + String.valueOf(anchor.getRow1()+1)+"," + String.valueOf(anchor.getCol1())+ "]_["+ String.valueOf(anchor.getRow2()+1)+"," + String.valueOf(anchor.getCol2())+"]";sheetIndexPicMap.put(picIndex, picData);}}}return sheetIndexPicMap;} else {return null;}}public static void printImg(List> sheetList,String filePath) throws IOException {for (Map map : sheetList) {Object key[] = map.keySet().toArray();for (int i = 0; i pictures = workbook.getAllPictures();Map map = new HashMap();System.out.println(pictures.size());for (int i = 0; i }

 User 自定义类

import java.awt.Color;import org.apache.poi.ss.usermodel.Cell;public class UserCell implements Comparable{private Cell cell;private int row;private int col;private boolean show;private String text="";private Color color=null;public Cell getCell() {return cell;}public void setCell(Cell cell) {this.cell = cell;}public int getRow() {return row;}public void setRow(int row) {this.row = row;}public int getCol() {return col;}public void setCol(int col) {this.col = col;}public boolean isShow() {return show;}public void setShow(boolean show) {this.show = show;}public String getText() {return text;}public void setText(String text) {this.text = text;}public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}@Overridepublic int compareTo(UserCell uc) {try{double meDouble=Double.parseDouble(this.getText().replaceAll("%", ""));double heDouble=Double.parseDouble(uc.getText().replaceAll("%", ""));if(meDoubleheDouble)return 1;}catch(Exception e){}return 0;}}

 

import java.awt.Color;
import java.awt.Font;import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFColor;
public class Grid {private boolean show;private int row; //对应Excel中的row,也可以理解为cells[i][j]的iprivate int col; //对应Excel中的col,也可以理解为cells[i][j]的jprivate int x; //x坐标private int y; //y坐标private int width;private int height;private String text;private java.awt.Font fOnt=new Font("微软雅黑",Font.PLAIN, 12);private java.awt.Color bgColor=null;private java.awt.Color ftColor=null;public int getRow() {return row;}public void setRow(int row) {this.row = row;}public int getCol() {return col;}public void setCol(int col) {this.col = col;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public boolean isShow() {return show;}public void setShow(boolean show) {this.show = show;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}public String getText() {return text;}public void setText(String text) {this.text = text;}public Color getBgColor() {return bgColor;}/*** 将poi.ss.usermodel.Color 转换成 java.awt.Color* @param color*/public void setBgColor(org.apache.poi.ss.usermodel.Color color) {this.bgColor=poiColor2awtColor(color);}public void setBgColor(java.awt.Color color){this.bgColor=color;}public Color getFtColor() {return ftColor;}public void setFtColor(org.apache.poi.ss.usermodel.Color color) {this.ftColor = poiColor2awtColor(color);}public Font getFont() {return font;}public void setFont(org.apache.poi.ss.usermodel.Font font) {if(font!=null){this.fOnt=new java.awt.Font(font.getFontName(),Font.BOLD,font.getFontHeight()/ 20+ 2); }}private java.awt.Color poiColor2awtColor(org.apache.poi.ss.usermodel.Color color){ java.awt.Color awtColor=null;if(color instanceof XSSFColor){ //.xlsxXSSFColor xc=(XSSFColor) color;String rgbHex=xc.getARGBHex();if(rgbHex!=null){awtColor=new Color(Integer.parseInt(rgbHex.substring( 2), 16));}}else if(color instanceof HSSFColor){ //.xlsHSSFColor hc=(HSSFColor) color;short[] s=hc.getTriplet();if(s!=null){awtColor=new Color(s[ 0],s[ 1],s[ 2]);}}return awtColor;}
}

 最后合起来将取出来的简称PPT

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;public class AddingImageToPPT {public static void main(String args[]) throws IOException, InvalidFormatException {/** 文件路径 **/ String filePath = "D:/ddd/testPng.pptx";String imagePath = "D://ddd//testBg.png";String imagePath2 = "D://ddd//test.png";String imagePath3 = "D://ddd//test.png";/** 加载PPT **/XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(filePath));/** 创建一个slide,理解为PPT里的每一页 **/XSLFSlide slide = ppt.createSlide();
// XSLFSlide slide2 = ppt.createSlide();XSLFSlide slide3 = ppt.createSlide();/** 生成二进制数组 **/byte[] pictureData = IOUtils.toByteArray(new FileInputStream(imagePath));byte[] pictureData2 = IOUtils.toByteArray(new FileInputStream(imagePath2));byte[] pictureData3 = IOUtils.toByteArray(new FileInputStream(imagePath3));/** 添加图片,返回索引 **/XSLFPictureData pictureIndex = ppt.addPicture(pictureData,PictureType.PNG);XSLFPictureData pictureIndex2 = ppt.addPicture(pictureData2, PictureType.PNG);XSLFPictureData pictureIndex3 = ppt.addPicture(pictureData3, PictureType.PNG);/** 打印信息 **/System.out.println("pictureIndex " + pictureIndex);// pictureIndex 0System.out.println("pictureIndex2 " + pictureIndex2);// pictureIndex2 1System.out.println("pictureIndex3 " + pictureIndex3);// pictureIndex3 2/** 创建图片 **/
// XSLFPictureShape pictureShape = slide.createPicture(pictureIndex);XSLFPictureShape pictureShape2 = slide.createPicture(pictureIndex2);XSLFPictureShape pictureShape3 = slide.createPicture(pictureIndex3);/** 设置图片的位置 四个参数分别为 x y width height **/
// pictureShape.setAnchor(new java.awt.Rectangle(2, 16,500,100));pictureShape2.setAnchor(new java.awt.Rectangle(2, 16, 500, 250));pictureShape3.setAnchor(new java.awt.Rectangle(2, 266, 500,250 ));/** 获取图片类别 **/
// PictureType pictureType = pictureShape.getPictureData().getType();// switch (pictureType){
// case JPEG:
// System.out.println("the type of picture is : " + "JPEG");
// break;
// case PNG:
// System.out.println("the type of picture is :" + "PNG");
// break;
// }// System.out.println(pictureType);/** 输出文件 **/ppt.write(new FileOutputStream(filePath));}
}

 


推荐阅读
  • 本文介绍了解决java开源项目apache commons email简单使用报错的方法,包括使用正确的JAR包和正确的代码配置,以及相关参数的设置。详细介绍了如何使用apache commons email发送邮件。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 展开全部下面的代码是创建一个立方体Thisexamplescreatesanddisplaysasimplebox.#Thefirstlineloadstheinit_disp ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • ***byte(字节)根据长度转成kb(千字节)和mb(兆字节)**parambytes*return*publicstaticStringbytes2kb(longbytes){ ... [详细]
  • 大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记
    本文介绍了大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记,包括outputFormat接口实现类、自定义outputFormat步骤和案例。案例中将包含nty的日志输出到nty.log文件,其他日志输出到other.log文件。同时提供了一些相关网址供参考。 ... [详细]
  • 本文介绍了关于Java异常的八大常见问题,包括异常管理的最佳做法、在try块中定义的变量不能用于catch或finally的原因以及为什么Double.parseDouble(null)和Integer.parseInt(null)会抛出不同的异常。同时指出这些问题是由于不同的开发人员开发所导致的,不值得过多思考。 ... [详细]
author-avatar
小女人hoffix_523
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有