package com.langtech.plm.tqsx; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFName; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFName; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.aspose.words.Bookmark; import com.aspose.words.Document; import com.aspose.words.Field; import com.aspose.words.SaveFormat; import com.teamcenter.rac.aif.AIFDesktop; import com.teamcenter.rac.aif.AbstractAIFApplication; import com.teamcenter.rac.aif.kernel.AbstractAIFSession; import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; import com.teamcenter.rac.kernel.TCComponent; import com.teamcenter.rac.kernel.TCComponentDataset; import com.teamcenter.rac.kernel.TCComponentItem; import com.teamcenter.rac.kernel.TCComponentItemRevision; import com.teamcenter.rac.kernel.TCComponentTcFile; import com.teamcenter.rac.kernel.TCException; import com.teamcenter.rac.kernel.TCProperty; import com.teamcenter.rac.util.FileUtility; public class PropertyToWordOrExcelOperation extends KOperation { public PropertyToWordOrExcelOperation(AbstractAIFApplication app, String opName) { super(app, opName, "正在执行。。。"); } final String preName = "Connor_LY6_WordExcel_Report_ItemType"; @Override public boolean init() throws Exception { new Thread().sleep(1000); InterfaceAIFComponent targetComponent = app.getTargetComponent(); TCComponentItemRevision revision = (TCComponentItemRevision) targetComponent; // 获取首选项里的值 String[] prefVals = KUtil.getPrefVals(session, preName); if(prefVals == null || prefVals.length == 0) { KUtil.info(AIFDesktop.getActiveDesktop(), preName + "该首选项未配置,请联系管理员!"); return false; } String relatioin = prefVals[0]; // 获取版本对象下的数据集对象 TCComponent[] relatedComponents = revision.getRelatedComponents(relatioin); if(relatedComponents == null || relatedComponents.length == 0) { KUtil.info(AIFDesktop.getActiveDesktop(), "选中对象的 " + relatioin + " 关系下没有数据集"); return false; } //处理首选项 HashMap nameMap = new HashMap();//数据集里面的名称和对象(item,rev,revMaster)集合 if(prefVals.length >= 2) { for (int i = 1; i < prefVals.length; i++) { //Item.object_name=object_name String[] split = prefVals[i].split("="); nameMap.put(split[1],split[0]); } } // 遍历数据集 for (TCComponent tcComponent : relatedComponents) { if (tcComponent instanceof TCComponentDataset) { TCComponentDataset dataset = (TCComponentDataset) tcComponent; // 工具包中获取系统临时变量的路径 File datasetFile = KUtil.getDatasetFile(dataset); String type = tcComponent.getType(); String datasetType = ""; String newPath = ""; if("MSExcel".equals(type) || "MSExcelX".equals(type) || "MSWord".equals(type) || "MSWordX".equals(type)) { switch (type) { case "MSExcel": datasetType = "excel"; newPath = dealExcel(datasetFile,revision,nameMap); break; case "MSExcelX": datasetType = "excel"; newPath = dealExcelX(datasetFile,revision,nameMap); break; case "MSWord": datasetType = "word"; newPath = dealWord2(datasetFile,revision,nameMap,"doc"); break; case "MSWordX": datasetType = "word"; newPath = dealWord2(datasetFile,revision,nameMap,"docx"); break; } //给数据集设置新的命名的引用 dataset.setFiles(new String[] {newPath}, new String[] {datasetType}); } } } KUtil.info(AIFDesktop.getActiveDesktop(), "提取对象版本属性到Word Excel执行完成"); return true; } @Override public void execute() throws Exception { } private String dealExcel(File datasetFile, TCComponentItemRevision revision, HashMap nameMap) throws IOException, TCException { FileInputStream is = new FileInputStream(datasetFile); HSSFWorkbook workbook = new HSSFWorkbook(is); List allNames = workbook.getAllNames(); for (HSSFName hssfName : allNames) { String name = hssfName.getNameName(); //名称管理器存在首选项的名称 if (nameMap.containsKey(name)) { CellReference cellReference = new CellReference(hssfName.getRefersToFormula()); HSSFSheet sheet = workbook.getSheet(cellReference.getSheetName()); HSSFRow row = sheet.getRow(cellReference.getRow()); HSSFCell cell = row.getCell(cellReference.getCol()); String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(name)); System.out.println("行为:" + cellReference.getRow() + "====" + "列为:" + cellReference.getCol() + "====" + "值为: " + preConfigValue); if(cell == null) { cell = row.createCell(cellReference.getCol()); } cell.setCellValue(preConfigValue); } } is.close(); FileOutputStream os = new FileOutputStream(datasetFile); workbook.write(os); workbook.close(); return datasetFile.getAbsolutePath(); } private String dealExcelX(File datasetFile, TCComponentItemRevision revision, HashMap nameMap) throws IOException, TCException { FileInputStream is = new FileInputStream(datasetFile); XSSFWorkbook workbook = new XSSFWorkbook(is); List allNames = workbook.getAllNames(); for (XSSFName xssfName : allNames) { String name = xssfName.getNameName(); //名称管理器存在首选项的名称 if (nameMap.containsKey(name)) { CellReference cellReference = new CellReference(xssfName.getRefersToFormula()); XSSFSheet sheet = workbook.getSheet(cellReference.getSheetName()); XSSFRow row = sheet.getRow(cellReference.getRow()); XSSFCell cell = row.getCell(cellReference.getCol()); String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(name)); System.out.println("行为:" + cellReference.getRow() + "====" + "列为:" + cellReference.getCol() + "====" + "值为: " + preConfigValue); if(cell == null) { cell = row.createCell(cellReference.getCol()); cell.setCellValue(preConfigValue); } else { cell.setCellValue(preConfigValue); } } } is.close(); FileOutputStream os = new FileOutputStream(datasetFile); workbook.write(os); workbook.close(); return datasetFile.getAbsolutePath(); } private String dealWord(File datasetFile, TCComponentItemRevision revision, HashMap nameMap,String type) throws IOException, TCException { String path = datasetFile.getAbsolutePath(); InputStream inputStream = Files.newInputStream(Paths.get(path)); Map dataMap = new HashMap<>(); for(String key : nameMap.keySet()) { String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(key)); dataMap.put(key, preConfigValue); } String newPath = ""; if(type.equals("doc")) { newPath = path.replace(".doc", "temp.doc"); WordUtils.replaceBookmarksByDoc(inputStream, Files.newOutputStream(Paths.get(newPath)), dataMap); } else if(type.equals("docx")) { newPath = path.replace(".docx", "temp.docx"); WordUtils.replaceBookmarksByDocx(inputStream, Files.newOutputStream(Paths.get(newPath)), dataMap); } return newPath; } private String dealWord2(File datasetFile, TCComponentItemRevision revision, HashMap nameMap,String type) throws FileNotFoundException, Exception { String path = datasetFile.getAbsolutePath(); Document document2 = new Document(new FileInputStream(path)); OutputStream outputStream = null; String newPath = path.replace(".doc", "temp.doc"); outputStream = new FileOutputStream(newPath); Map dataMap = new HashMap<>(); for(String key : nameMap.keySet()) { String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(key)); System.out.println("dataMap("+key+","+preConfigValue+")"); dataMap.put(key, preConfigValue); } // 遍历文档中所有的书签 for (Bookmark bookmark : document2.getRange().getBookmarks()) { String bookmarkName = bookmark.getName(); System.out.println("书签名:"+bookmarkName); if(dataMap.containsKey(bookmarkName)) { System.out.println("添加内容"); bookmark.setText(dataMap.get(bookmarkName)); } } // 遍历文档中的所有域 for (Field field : document2.getRange().getFields()) { // 获取域的名称 String fieldName = field.getFieldCode(); System.out.println("域名:" + fieldName); for(String key : dataMap.keySet()) { // 根据字段类型或其他条件设置值 if(fieldName.contains(key)) {// 假设您想处理表单输入域 System.out.println("添加内容"); field.setResult(dataMap.get(key)); // 设置域的值 } } } if(type.equals("doc")) { document2.save(outputStream, SaveFormat.DOC); }else if(type.equals("docx")) { document2.save(outputStream, SaveFormat.DOCX); } return newPath; } /** * 得到首选项中“=”左边对应的属性值 * @param revision * @param nameMap * @param value * @return * @throws TCException */ private String getPreConfigValue(TCComponentItemRevision revision, HashMap nameMap,String value) throws TCException { String[] split = value.split("\\."); String cellValue = ""; TCProperty property = null; if(split.length == 2) { switch (split[0]) { case "Item": property = revision.getItem().getTCProperty(split[1]); break; case "Rev": property = revision.getTCProperty(split[1]); break; case "RevMaster": property = revision.getRelatedComponent("IMAN_master_form_rev").getTCProperty(split[1]); break; default: break; } } //取关系文件夹下的属性 else if(split.length == 3) { String relation = split[0]; TCComponent relatedComponent = revision.getRelatedComponent(relation); TCComponentItemRevision centerRev = null; if(relatedComponent instanceof TCComponentItemRevision) { centerRev = (TCComponentItemRevision) relatedComponent; }else if(relatedComponent instanceof TCComponentItem) { centerRev = ((TCComponentItem) relatedComponent).getLatestItemRevision(); } if(centerRev != null) { switch (split[1]) { case "Item": property = centerRev.getItem().getTCProperty(split[2]); break; case "Rev": property = centerRev.getTCProperty(split[2]); break; case "RevMaster": property = centerRev.getRelatedComponent("IMAN_master_form_rev").getTCProperty(split[2]); break; default: break; } } } if(property == null) { return ""; } else { cellValue = property.getDisplayValue(); return cellValue; } } }