contribucion inspecionar archivos office por dentro

Iniciado por sapito169, 5 Octubre 2021, 01:03 AM

0 Miembros y 1 Visitante están viendo este tema.

sapito169

les presento una herramienta para que puedan ver sus  documento word excel y ppt de office 2003 2007 desde adentro

en futuras entregas mejorare la herramienta para que pueda comparar archivos de office
y también hacer una super búsqueda en varios archivos de office

Código (java) [Seleccionar]

package office;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;

import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;

public class TreeViewExample extends Application {

Stage primaryStage;
BorderPane root;
Map<String, TreeItem> map;
Map<String, String> inmemory;
  CodeArea textArea = new    CodeArea();
  TextField label  = new TextField("File:");

private static final Pattern XML_TAG = Pattern.compile("(?<ELEMENT>(</?\\h*)(\\w+)([^<>]*)(\\h*/?>))"
+"|(?<COMMENT><!--[^<>]+-->)");

private static final Pattern ATTRIBUTES = Pattern.compile("(\\w+\\h*)(=)(\\h*\"[^\"]+\")");

private static final int GROUP_OPEN_BRACKET = 2;
private static final int GROUP_ELEMENT_NAME = 3;
private static final int GROUP_ATTRIBUTES_SECTION = 4;
private static final int GROUP_CLOSE_BRACKET = 5;
private static final int GROUP_ATTRIBUTE_NAME = 1;
private static final int GROUP_EQUAL_SYMBOL = 2;
private static final int GROUP_ATTRIBUTE_VALUE = 3;


public static void main(String[] args) {
Application.launch(args);

}

public void open(ActionEvent actionEvent) {
textArea.clear();
inmemory=new HashMap<String, String>();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("selecione el excel");

fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Excel", "*.xlsx"),
new ExtensionFilter("Doc", "*.docx"), new ExtensionFilter("Ppt", "*..pptx"));
File file = fileChooser.showOpenDialog(primaryStage);

if (file != null) {
label.setText(file.getAbsolutePath());
try (ZipFile zipFile = new ZipFile(file);) {

Enumeration<?> enu = zipFile.entries();
Set<String> nodes = new HashSet<>();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();

InputStream inputStream= zipFile.getInputStream(zipEntry);



String name = zipEntry.getName();

inmemory.put(name+"/", convertToString(inputStream));
inputStream.close();
String[] split = name.split("/");



String node = "";
for (String current : split) {
node += current + "/";
nodes.add(node);
}

}
List<String> listnodes = new ArrayList<String>(nodes);

Collections.sort(listnodes, this::compare);

TreeItem rootItem = root(listnodes, file.getName());

TreeView treeView = new TreeView();
treeView.getSelectionModel().selectedItemProperty().addListener(this::selectedFile);
treeView.setRoot(rootItem);

treeView.setShowRoot(true);

root.setLeft(treeView);

} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(e.getMessage());
e.printStackTrace();
alert.showAndWait();
}

}

}

String convertToString(InputStream in){
   Scanner scanner = new Scanner(in);
   scanner.useDelimiter("\\A");

   boolean hasInput = scanner.hasNext();
   if (hasInput) {
       return scanner.next();
   } else {
       return null;
   }

}

void selectedFile(ObservableValue observable, Object oldValue,
           Object newValue){
       TreeItem<String> selectedItem = (TreeItem<String>) newValue;
        for(String current: map.keySet()) {
        if(map.get(current)==selectedItem) {
        String text=inmemory.get(current);
        if(text!=null) {
        textArea.replaceText(prettyFormat(text));
        }
        }
        }
}

public int compare(String o1, String o2) {
int result = (Integer.valueOf(o1.split("/").length)).compareTo(o2.split("/").length);
if (result == 0)
result = o1.compareTo(o2);
return result;
}

private TreeItem root(List<String> listnodes, String name) {

TreeItem rootItem = new TreeItem(name);

rootItem.setExpanded(true);
map = new LinkedHashMap<String, TreeItem>();
for (String current : listnodes) {
String[] split = current.substring(0, current.length() - 1).split("/");

map.put(current, new TreeItem(split[split.length - 1]));
}

for (String key : map.keySet()) {

if (key.split("/", -1).length == 2) {

rootItem.getChildren().add(map.get(key));

} else {

String currentName = map.get(key).getValue() + "";
String result = key.substring(0, key.lastIndexOf(currentName + "/"));

TreeItem parent = map.get(result);
parent.setExpanded(true);
parent.getChildren().add(map.get(key));

}

}

return rootItem;
}



public String prettyFormat(String xml) {

       try {
           final InputSource src = new InputSource(new StringReader(xml));
           final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
           final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

       //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");


           final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
           final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
           final LSSerializer writer = impl.createLSSerializer();

           writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
           writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.

           return writer.writeToString(document);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }

@Override
public void start(Stage primaryStage) {  
label.setEditable(false);
label.setStyle("-fx-background-color:#ced1d6;");
textArea.setParagraphGraphicFactory(LineNumberFactory.get(textArea));
this.primaryStage = primaryStage;
Menu m = new Menu("Archivo");

MenuItem open = new MenuItem("Inspect");


open.setOnAction(this::open);
m.getItems().add(open);

MenuBar mb = new MenuBar();
mb.getMenus().add(m);

root = new BorderPane();

VBox head = new VBox();
head.getChildren().add(mb);
head.getChildren().add(label);
root.setTop(head);


textArea.setEditable(false);
textArea.textProperty().addListener((obs, oldText, newText) -> {
textArea.setStyleSpans(0, computeHighlighting(newText));
       });
root.setCenter(new VirtualizedScrollPane<>(textArea));

Scene scene = new Scene(root, 550, 250);
scene.getStylesheets().add(TreeViewExample.class.getResource("xml-highlighting.css").toExternalForm());
primaryStage.setTitle("OpenXml Comparator");
primaryStage.setScene(scene);
// primaryStage.setMaximized(true);

primaryStage.show();

}
private static StyleSpans<Collection<String>> computeHighlighting(String text) {
   
       Matcher matcher = XML_TAG.matcher(text);
       int lastKwEnd = 0;
       StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
       while(matcher.find()) {
       
        spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
        if(matcher.group("COMMENT") != null) {
        spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start());
        }
        else {
        if(matcher.group("ELEMENT") != null) {
        String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION);
       
        spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET));
        spansBuilder.add(Collections.singleton("anytag"), matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET));

        if(!attributesText.isEmpty()) {
       
        lastKwEnd = 0;
       
        Matcher amatcher = ATTRIBUTES.matcher(attributesText);
        while(amatcher.find()) {
        spansBuilder.add(Collections.emptyList(), amatcher.start() - lastKwEnd);
        spansBuilder.add(Collections.singleton("attribute"), amatcher.end(GROUP_ATTRIBUTE_NAME) - amatcher.start(GROUP_ATTRIBUTE_NAME));
        spansBuilder.add(Collections.singleton("tagmark"), amatcher.end(GROUP_EQUAL_SYMBOL) - amatcher.end(GROUP_ATTRIBUTE_NAME));
        spansBuilder.add(Collections.singleton("avalue"), amatcher.end(GROUP_ATTRIBUTE_VALUE) - amatcher.end(GROUP_EQUAL_SYMBOL));
        lastKwEnd = amatcher.end();
        }
        if(attributesText.length() > lastKwEnd)
        spansBuilder.add(Collections.emptyList(), attributesText.length() - lastKwEnd);
        }

        lastKwEnd = matcher.end(GROUP_ATTRIBUTES_SECTION);
       
        spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_CLOSE_BRACKET) - lastKwEnd);
        }
        }
           lastKwEnd = matcher.end();
       }
       spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
       return spansBuilder.create();
   }
}


Código (visualfoxpro) [Seleccionar]
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tool</groupId>
<artifactId>office</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.fxmisc.richtext</groupId>
<artifactId>richtextfx</artifactId>
<version>0.10.6
   </version>
</dependency>
</dependencies>

</project>



Código (css) [Seleccionar]
.tagmark {
   -fx-fill: gray;
}
.anytag {
   -fx-fill: crimson;
}
.paren {
   -fx-fill: firebrick;
   -fx-font-weight: bold;
}
.attribute {
   -fx-fill: darkviolet;
}
.avalue {
   -fx-fill: black;
}

.comment {
-fx-fill: teal;
}

.red-text {
   -fx-font-color: red;
}
.red-green {
   -fx-font-color: blue;
}
.styleClassName {

       -fx-background-color:gray;

    }