aspose.word导出word文档

时间:2024-03-25 08:46:19

第一步,word模板的处理

1.选中要处理的部分,点击插入,找到文档部件

aspose.word导出word文档

2.选中域

aspose.word导出word文档

做如下操作:

aspose.word导出word文档

第二步:后台代码的编写

package net.ghsoft.calibration.modules.common.utils;






import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;


import java.util.HashMap;


import java.util.Map;
import java.util.regex.Pattern;


import com.aspose.words.Document;
import com.aspose.words.FindReplaceOptions;
import net.ghsoft.calibration.modules.resultoutput.entity.Result;
import net.ghsoft.general.common.utils.StringUtils;




public class WordUtils {
private static Map<String, String> dataMap = new HashMap<String, String>();


public static Document createDoc(Result result,  String path,String outPath) throws Exception{ 
    dataMap=getMap(result);
    Document doc = new Document(path);
   for(String key:dataMap.keySet()) {
     doc.getRange().replace(key, dataMap.get(key), false, false);
    }

    doc.save(outPath);
   return doc;
    }  
 
      public static Map<String, String> getMap(Result result) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
      Field[] fields = result.getClass().getDeclaredFields();
      String fieldName="";
      for (int i = 1; i < fields.length; i++) {
      fieldName= fields[i].getName().substring(0, 1).toUpperCase()+fields[i].getName().substring(1);
            String value =(String) result.getClass().getMethod("get" +fieldName).invoke(result);
           if(!StringUtils.isEmpty(value)) {
          dataMap.put(fieldName, value);
           } 
   
return dataMap;
      }


}


public class Test {


public static void main(String[] args) {

                Result  result = new Result();

                result.setName="张三";   

                result.setDay=“2018-04-19”;

                result.setWarn="开除";


InputStream inputStream = null;
OutputStream outputStream = null;
String filePath =  "";//文件路径
try {

Document doc = WordUtils .createReport(list.get(0), filePath);
inputStream = new BufferedInputStream(doc);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
response.reset();
String fileName ="";//文件ming
response.addHeader("Content-Disposition", "attchment;filename=" + fileName);
response.setContentType("application/octet-stream");
outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(buffer);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
throw new OperationException("取消提交公示信息失败,请联系系统管理员!", e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

     

               

}  
}