poi 작업 PPT 읽 기 템 플 릿 흐름, 새 PPT 파일 생 성
java PPT , value key , , , 。
org.apache.poi
poi
3.15
org.apache.poi
poi-scratchpad
3.15
org.apache.poi
poi-ooxml
3.15
SystemControllerLog(description = " PPT")
@GetMapping(value = "/createPPTByTemplate")
public void createPPTByTemplate(ProductPoiModel productPoiModel,HttpServletRequest req, HttpServletResponse httpServletResponse) throws SystemException, IOException, ExecutionException, InterruptedException {
// File file = new File("C:\\Users\\Admin\\Desktop\\POI\\ -0622.pptx");
ProductDetailModel productDetailModel = new ProductDetailModel();
productDetailModel.setId(productPoiModel.getProductId());
ProductDetailModel productDetail = productService.getDetailById(productDetailModel);
String productOverview = productDetail.getOverview();
String picture = null;
if(StringUtils.isNotNull(productOverview) && productOverview.contains("src")) {
System.out.print(" , ");
List stringList = this.getImgSrc(productOverview);
picture = stringList.get(0);
}else {
picture = "null";
}
InputStream is = null;
Map map = new HashMap<>();
String allData = null;
Result result = null;
Object[][] creditDatas = null;
Object[][] datas = null;
StringBuffer devBuffer = new StringBuffer();
String enterpriseBusiness = null; //
try {
is = this.getClass().getClassLoader().getResourceAsStream("template/service_proposal_template.pptx");
// PowerPoint ,
allData = this.getCompanyDetail(productPoiModel.getCompanyFullName());
JSONObject json = JSONObject.fromObject(allData);
Map hashMap = new HashMap<>();
hashMap.put("taxcredits",Taxcredit.class);
hashMap.put("products",Product.class);
hashMap.put("owntaxes",Owntax.class);
ProductPoiModel poiModel = (ProductPoiModel)JSONObject.toBean(json, ProductPoiModel.class,hashMap);
result = poiModel.getResult();
} catch (Exception e) {
logger.error(e.getMessage());
System.out.print("----JSONObject-------"+e.getMessage());
}
if (result == null || StringUtils.isNull(result)) {
creditDatas = new Object[1][1];
creditDatas[0][0] = "null";
datas = new Object[1][1];
datas[0][0] = "null";
devBuffer.append(" XXX ");
enterpriseBusiness = devBuffer.toString();
} else {
//
if ((result.getTaxcredits() != null) && (result.getTaxcredits().size() >= 1)) {
List operateList = result.getTaxcredits();
creditDatas = new Object[operateList.size() + 1][5];
creditDatas[0][0] = " ";
creditDatas[0][1] = " ";
creditDatas[0][2] = " ";
creditDatas[0][3] = " ";
creditDatas[0][4] = " ";
for (int i = 0; i < operateList.size(); i++) {
creditDatas[i + 1][0] = operateList.get(i).getYear();
creditDatas[i + 1][1] = operateList.get(i).getGrade();
creditDatas[i + 1][2] = operateList.get(i).getType();
creditDatas[i + 1][3] = operateList.get(i).getIdNumber();
creditDatas[i + 1][4] = operateList.get(i).getEvalDepartment();
}
} else {
creditDatas = new Object[1][1];
creditDatas[0][0] = "null";
}
if ((result.getOwntaxes() != null) && (result.getOwntaxes().size() >= 1)) {
List blist = result.getOwntaxes();
datas = new Object[blist.size() + 1][7];
datas[0][0] = " ";
datas[0][1] = " ";
datas[0][2] = " ";
datas[0][3] = " ";
datas[0][4] = " ";
datas[0][5] = " ";
datas[0][6] = " ";
for (int i = 0; i < blist.size(); i++) {
datas[i + 1][0] = blist.get(i).getPublishDate();
datas[i + 1][1] = blist.get(i).getPersonIdNumber();
datas[i + 1][2] = blist.get(i).getTaxCategory();
datas[i + 1][3] = blist.get(i).getType();
datas[i + 1][4] = blist.get(i).getOwnTaxAmount();
datas[i + 1][5] = blist.get(i).getNewOwnTaxBalance();
datas[i + 1][6] = blist.get(i).getDepartment();
}
} else {
datas = new Object[1][1];
datas[0][0] = "null";
}
if ((result.getProducts() != null) && (result.getProducts().size() >= 1)) {
List plist = result.getProducts();
for (int i = 0; i < plist.size(); i++) {
devBuffer.append(plist.get(i).getYewu() + "、");
}
} else if (result.getProducts() == null || result.getProducts().size() < 1) {
devBuffer.append(" XXX ");
enterpriseBusiness = devBuffer.toString();
}
if (!("".equals(devBuffer.toString())) && (!" XXX ".equals(devBuffer.toString()))) {
devBuffer.deleteCharAt(devBuffer.length() - 1);
enterpriseBusiness = devBuffer.toString();
}
}
//
map.put("page_1_text_1", productPoiModel.getCompanyFullName());//
map.put("page_1_text_2", productDetail.getProductName());//
map.put("page_4_text_1", productPoiModel.getCompanyFullName());//
map.put("page_4_text_2", enterpriseBusiness);// 2.3 1、 2
map.put("page_4_text_3", productDetail.getProductName());//
map.put("page_5_table_1",datas);//
map.put("page_6_table_1",creditDatas);//
map.put("page_10_Img_1",picture);// overview
// InputStream powerPoint = new FileInputStream(file);
InputStream powerPoint = is;
if(powerPoint == null) {
return ;
}
XMLSlideShow slideShow = new XMLSlideShow(powerPoint);
List slides = slideShow.getSlides();
for (int i = 0 ; i < slides.size() ; i++) {
List shapes = ((Slide)slides.get(i)).getShapes();
for (int j = 0 ; j < shapes.size() ; j++) {
Shape shape = (Shape) shapes.get(j);
PowerPoint2007FileUtil.renderShape(shape, map, slideShow,i);
}
}
// OutputStream outputStreams = new FileOutputStream("C:\\Users\\Admin\\Desktop\\test.pptx");
httpServletResponse.setContentType("octets/stream");
String excelName = productDetail.getProductName() + ProductContant.BIG_DATA_PPT_NAME;
httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".pptx");
OutputStream outputStreams = httpServletResponse.getOutputStream();
slideShow.write(outputStreams);
}
package com.atme8.product.core.utils.poi;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;
import com.atme8.product.core.contant.ProductContant;
import com.atme8.tax.cloud.core.util.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.poi.sl.draw.DrawPictureShape;
import org.apache.poi.sl.draw.geom.CustomGeometry;
import org.apache.poi.sl.draw.geom.Guide;
import org.apache.poi.sl.usermodel.*;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.xslf.usermodel.*;
import static org.apache.poi.sl.usermodel.StrokeStyle.LineCompound.THICK_THIN;
import static org.apache.poi.sl.usermodel.StrokeStyle.LineCompound.THIN_THICK;
/**
* PowerPoint
*
*
PowerPoint , PowerPoint
*/
public class BasePowerPointFileUtil {
/**
*
PowerPoint
*
* @param slideShow SlideShow
* @return
*/
public static List readSlideShow(SlideShow slideShow) {
List slideList = null;
if (slideShow != null) {
slideList = new ArrayList();
List slides = slideShow.getSlides();
for (int i = 0; i < slides.size(); i++) {
slideList.add(BasePowerPointFileUtil.readSlide((Slide) slides.get(i)));
}
}
return slideList;
}
/**
*
Slide
*
* @param slide Slide
* @return Slide
*/
public static List readSlide(Slide slide) {
List shapeList = null;
if (slide != null) {
shapeList = new ArrayList();
List shapes = slide.getShapes();
for (int i = 0; i < shapes.size(); i++) {
shapeList.add(BasePowerPointFileUtil.readShape((Shape) shapes.get(i)));
}
}
return shapeList;
}
/**
*
*
* @param shape Slide
* @return
*/
public static Object readShape(Shape shape) {
String returnValue = null;
if (shape != null) {
if (shape instanceof TextShape) {
try {
returnValue = ((TextShape) shape).getText();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return returnValue;
}
public static void renderShape(Shape shape, Map data,XMLSlideShow ppt,int i) throws IOException {
if (shape instanceof TextShape) {
BasePowerPointFileUtil.replace(shape, data, ppt,i);
} else if (shape instanceof GroupShape) {
Iterator groupShapes = ((GroupShape) shape).iterator();
while (groupShapes.hasNext()) {
Shape groupShape = (Shape) groupShapes.next();
BasePowerPointFileUtil.renderShape(groupShape, data, ppt,i);
}
} else if (shape instanceof TableShape) {
TableShape tableShape = ((TableShape) shape);
int column = tableShape.getNumberOfColumns();
int row = tableShape.getNumberOfRows();
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
BasePowerPointFileUtil.replace(tableShape.getCell(r, c), data, ppt, i);
}
}
}
// else if (shape instanceof PictureShape) {
// PictureShape pictureShape = ((PictureShape) shape);
// PictureData pictureData = pictureShape.getPictureData();
// String url = "http://img.atme8.com/Fi8XLHpB-XYOq7NJHIVCA2OqysTN";
// byte[] btImg = getImageFromNetByUrl(url);
// pictureData.setData(btImg);
// byte[] b = pictureData.getData();
// System.out.println(pictureShape);
// }
}
/**
*
* @param strUrl
* @return
*/
private static byte[] getImageFromNetByUrl(String strUrl){
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//
byte[] btImg = readInputStream(inStream);//
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param inStream
* @return
* @throws Exception
*/
private static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public static void replace(Shape shape, Map data,XMLSlideShow ppt,int i) throws IOException {
if(data == null) {
data = new HashMap<>();
}
if (shape instanceof TextShape) {
TextShape textShape = (TextShape) shape;
String text = textShape.getText();
List keys = DealStrSubUtil.getSubUtil(text, "\\$\\{(.+?)\\}");
Map map = (Map) data;
for (String key : keys) {
Object value = map.get(key);
if (value != null) {
if(key.contains("text")) {
text = text.replaceAll("\\$\\{" + key + "\\}", value.toString());
// text = text.replaceAll("\\r\
|\\r|\
|\
\\r", "");
textShape.setText(text);
// for(int j = 0 ; j < textShape.getTextParagraphs().size() ; j ++) {
// XSLFTextParagraph xh = (XSLFTextParagraph) textShape.getTextParagraphs().get(j);
//
// XSLFTextRun xslfTextRun = xh.getTextRuns().get(0);
// if (j % 2 != 0){
// xslfTextRun.setFontSize(12d);
// }
//
for (int k = 0; k < xh.getTextRuns().size(); k++) {
XSLFTextRun xslfTextRun = xh.getTextRuns().get(k);
if (j % 2 != 0)
xslfTextRun.setFontSize(12d);
}
// }
}
if(key.contains("Img")) {
if(!"null".equals(value)) {
//
byte[] btImg = getImageFromNetByUrl(value.toString());
XSLFPictureData idx = ppt.addPicture(btImg, XSLFPictureData.PictureType.JPEG);
List slides = ppt.getSlides();
XSLFSlide slide = slides.get(i);
XSLFPictureShape pic = slide.createPicture(idx);
Rectangle2D anchor = shape.getAnchor();
// XSLFPictureShape
pic.setAnchor(anchor);
// XSLFTextShape
slide.removeShape((XSLFShape) shape);
}else {
text = text.replaceAll("\\$\\{" + key + "\\}", ProductContant.NULL_PICTURE_TEXT_NOTICE);
textShape.setText(text);
for(int j = 0 ; j < textShape.getTextParagraphs().size() ; j ++) {
XSLFTextParagraph xh = (XSLFTextParagraph) textShape.getTextParagraphs().get(j);
XSLFTextRun xslfTextRun = xh.getTextRuns().get(0);
xslfTextRun.setFontSize(18d);
xslfTextRun.setFontColor(Color.red);
}
}
}
if(key.contains("table")) {
Object[][] objects = (Object[][]) value;
if("page_5_table_1".equals(key) && objects[0][0].equals("null")){
text = text.replaceAll("\\$\\{" + key + "\\}", ProductContant.NULL_Table_TEXT_TAX_NOTICE);
textShape.setText(text);
for(int j = 0 ; j < textShape.getTextParagraphs().size() ; j ++) {
XSLFTextParagraph xh = (XSLFTextParagraph) textShape.getTextParagraphs().get(j);
XSLFTextRun xslfTextRun = xh.getTextRuns().get(0);
xslfTextRun.setFontSize(18d);
xslfTextRun.setFontColor(new Color(1, 4, 8));
xslfTextRun.setBold(true);
}
textShape.setHorizontalCentered(true);
textShape.setVerticalAlignment(VerticalAlignment.TOP);
}else if ("page_6_table_1".equals(key) && objects[0][0].equals("null")){
text = text.replaceAll("\\$\\{" + key + "\\}", ProductContant.NULL_TABLE_TEXT_TAX_CREDITS_NOTICE);
textShape.setText(text);
for(int j = 0 ; j < textShape.getTextParagraphs().size() ; j ++) {
XSLFTextParagraph xh = (XSLFTextParagraph) textShape.getTextParagraphs().get(j);
XSLFTextRun xslfTextRun = xh.getTextRuns().get(0);
xslfTextRun.setBold(true);
xslfTextRun.setFontSize(18d);
xslfTextRun.setFontColor(new Color(1, 4, 8));
}
textShape.setHorizontalCentered(true);
textShape.setVerticalAlignment(VerticalAlignment.TOP);
} else {
Object[][] datas = (Object[][]) value;
/** **/
XSLFSlide slide = ppt.getSlides().get(i);
XSLFTable table = slide.createTable();
/** x ,y ,width,height **/
Rectangle2D rectangle2D = new Rectangle2D.Double(30,150,900,500);
// Rectangle2D rectangle2D = shape.getAnchor();
table.setAnchor(rectangle2D);
for(int x = 0; x < datas.length; x++) {
XSLFTableRow tableRow = table.addRow(); //
for(int y = 0; y < datas[x].length; y++) {
tableRow.setHeight(20);
XSLFTableCell tableCell = tableRow.addCell();//
XSLFTextParagraph p = tableCell.addNewTextParagraph();
XSLFTextRun tr = p.addNewTextRun();
tr.setBold(true);
if(x == 0) {
tr.setFontSize(10d);
p.setTextAlign(TextParagraph.TextAlign.CENTER);
}else {
tr.setFontSize(10d);
}
tr.setText(String.valueOf(datas[x][y]));
tableCell.setBorderColor(TableCell.BorderEdge.bottom,new Color(134, 134, 134));
tableCell.setBorderColor(TableCell.BorderEdge.top,new Color(134, 134, 134));
tableCell.setBorderColor(TableCell.BorderEdge.left,new Color(134, 134, 134));
tableCell.setBorderColor(TableCell.BorderEdge.right,new Color(134, 134, 134));
StrokeStyle style = new StrokeStyle() {
@Override
public PaintStyle getPaint() {
return null;
}
@Override
public LineCap getLineCap() {
return null;
}
@Override
public LineDash getLineDash() {
return null;
}
@Override
public LineCompound getLineCompound() {
return null;
}
@Override
public double getLineWidth() {
return 0.11d;
}
};
table.setColumnWidth(y,900/datas[x].length);
}
}
text = text.replaceAll("\\$\\{" + key + "\\}", "");
textShape.setText(text);
}
}
}
if(value == null && key.contains("Img")) {
text = text.replaceAll("\\$\\{" + key + "\\}", "");
textShape.setText(text);
}
}
}
}
}
package com.atme8.product.core.utils.poi;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by majun on 2017/10/16.
*/
public class DealStrSubUtil {
/**
*
* @param soap
* @return
*/
public static List getSubUtil(String soap, String rgex){
List list = new ArrayList();
Pattern pattern = Pattern.compile(rgex);//
Matcher m = pattern.matcher(soap);
while (m.find()) {
int i = 1;
list.add(m.group(i));
i++;
}
return list;
}
/**
* , , getSubUtil
* @param soap
* @param rgex
* @return
*/
public static String getSubUtilSimple(String soap,String rgex){
Pattern pattern = Pattern.compile(rgex);//
Matcher m = pattern.matcher(soap);
while(m.find()){
return m.group(1);
}
return "";
}
}
package com.atme8.product.core.utils.poi;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.sl.usermodel.AutoShape;
import org.apache.poi.sl.usermodel.GroupShape;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
/**
* PowerPoint2007
*
*
PowerPoint2007 , PowerPoint
*
*/
public class PowerPoint2007FileUtil extends BasePowerPointFileUtil {
/**
*
PowerPoint
*
* @param powerPointFile PowerPoint
* @param shapeSeparator Shape
* @param slideSeparator Slide
*
* @return
*
*/
public static String extractTextFromPowerPointFile(File powerPointFile , String shapeSeparator , String slideSeparator) {
StringBuffer returnValue = new StringBuffer();
if (powerPointFile != null && slideSeparator != null && shapeSeparator != null) {
if (powerPointFile.isFile()) {
try {
XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream(powerPointFile));
Iterator slideIterator = PowerPoint2007FileUtil.readSlideShow(slideShow).iterator();
// Slide
while (slideIterator.hasNext()) {
Iterator shapeIterator = ((List) slideIterator.next()).iterator();
// Shape
while (shapeIterator.hasNext()) {
Object shapeValue = shapeIterator.next();
if (shapeValue != null) {
returnValue.append((String) shapeValue);
if (shapeIterator.hasNext()) {
returnValue.append(shapeSeparator);
}
}
}
if (slideIterator.hasNext()) {
returnValue.append(slideSeparator);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return StringUtils.trimToNull(returnValue.toString());
}
// public static void renderPowerPointTemplate(InputStream powerPoint, Map data) throws IOException {
// if(powerPoint == null) {
// return;
// }
// XMLSlideShow slideShow = new XMLSlideShow(powerPoint);
// List slides = slideShow.getSlides();
// for (int i = 0 ; i < slides.size() ; i++) {
//
// List shapes = ((Slide)slides.get(i)).getShapes();
// for (int j = 0 ; j < shapes.size() ; j++) {
// Shape shape = (Shape) shapes.get(j);
// PowerPoint2007FileUtil.renderShape(shape, data);
// }
// }
// OutputStream outputStreams = new FileOutputStream("C:\\Users\\Admin\\Desktop\\test.pptx");
// slideShow.write(outputStreams);
// }
}
package com.atme8.product.core.utils.poi;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.sl.usermodel.SlideShow;
/**
* PowerPoint2003
*
*
PowerPoint2003 , PowerPoint
*
*/
public class PowerPoint2003FileUtil extends BasePowerPointFileUtil {
/**
*
PowerPoint
*
* @param powerPointFile PowerPoint
* @param shapeSeparator Shape
* @param slideSeparator Slide
*
*/
public static String extractTextFromPowerPointFile(File powerPointFile , String shapeSeparator , String slideSeparator) {
StringBuffer returnValue = new StringBuffer();
if (powerPointFile != null && slideSeparator != null && shapeSeparator != null) {
if (powerPointFile.isFile()) {
try {
SlideShow slideShow = new HSLFSlideShow(new HSLFSlideShowImpl(powerPointFile.getCanonicalPath()));
Iterator slideIterator = PowerPoint2003FileUtil.readSlideShow(slideShow).iterator();
// Slide
while (slideIterator.hasNext()) {
Iterator shapeIterator = ((List) slideIterator.next()).iterator();
// Shape
while (shapeIterator.hasNext()) {
Object shapeValue = shapeIterator.next();
if (shapeValue != null) {
returnValue.append((String) shapeValue);
if (shapeIterator.hasNext()) {
returnValue.append(shapeSeparator);
}
}
}
if (slideIterator.hasNext()) {
returnValue.append(slideSeparator);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return StringUtils.trimToNull(returnValue.toString());
}
}
package com.atme8.product.core.utils.poi;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
/**
* PowerPoint
*
*
PowerPoint , PowerPoint
*
* @author , [email protected]
* @since AiyuCommonCore-1.0
* @version AiyuCommonCore-1.0
*/
public class PowerPointFileUtil extends BasePowerPointFileUtil {
/**
*
PowerPoint
*
* @param powerPointFile PowerPoint
* @param shapeSeparator Shape
* @param slideSeparator Slide
*
* @return
*
* @modify , 2017-02-06
*/
public static String extractTextFromPowerPointFile(File powerPointFile , String shapeSeparator , String slideSeparator) {
String resultText = null;
if (powerPointFile != null && powerPointFile.exists()) {
String extension = FilenameUtils.getExtension(powerPointFile.getName());
if (StringUtils.equalsIgnoreCase("ppt" , extension)) {
//Office2003
resultText = PowerPoint2003FileUtil.extractTextFromPowerPointFile(powerPointFile , shapeSeparator , slideSeparator);
} else if (StringUtils.equalsIgnoreCase("pptx" , extension)) {
//Office2007
resultText = PowerPoint2007FileUtil.extractTextFromPowerPointFile(powerPointFile , shapeSeparator , slideSeparator);
} else {
//
}
}
return resultText;
}
ppt ${page_1_text_1 } value
:https://download.csdn.net/download/ccmedu/10378575
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.