I need to open a .dotx document, modify the content (or something similar) and put my own data, and then return generated .docx/document.
for exemple in the dotx file, the string "name" should be replaced by "John" in genrated docx file.
public static void main( String[] args ) throws IOException
{
String inputFile="D:/Copies 2.dotx";
// String outputeFile="D:/test.txt";
String outputeFile="D:/test.docx";
File inFile=new File(inputFile);
File ouFile=new File(outputeFile);
Map<String,String> hm = new HashMap<String,String>();
hm.put("Namur","Youssef");
App a = new App();
a.changeData(inFile,ouFile, hm);
}
private void changeData(File targetFile,File out, Map<String,String> substitutionData) throws IOException{
BufferedReader br = null;
String docxTemplate = "";
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile)));
String temp;
while( (temp = br.readLine()) != null) {
docxTemplate = docxTemplate + temp;
}
br.close();
}
catch (IOException e) {
br.close();
throw e;
}
Iterator<Entry<String, String>> substitutionDataIterator = substitutionData.entrySet().iterator();
while(substitutionDataIterator.hasNext()){
Map.Entry<String,String> pair = (Map.Entry<String,String>)substitutionDataIterator.next();
if(docxTemplate.contains(pair.getKey())){
if(pair.getValue() != null)
docxTemplate = docxTemplate.replace(pair.getKey(), pair.getValue());
else
docxTemplate = docxTemplate.replace(pair.getKey(), "NEDOSTAJE");
}
}
FileOutputStream fos = null;
try{
fos = new FileOutputStream(out);
fos.write(docxTemplate.getBytes());
fos.close();
}
catch (IOException e) {
fos.close();
throw e;
}
}
Can someone give me some advice on this?
Ps: i'm using apach POI 3.16