如何从java中的文档模板生成动态word文档?

uinbv5nw  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(431)

我有一个word文档模板,在这里我必须从java对象动态填充值。文档模板将位于项目类路径中,我必须动态填充这些值,并将同一个文件保存到共享文件夹位置。
我使用jcifs将文件保存到受限制的共享位置。文件创建成功,但内容生成不正确。下面是代码,

String user = "username:pwd";
String fileName = outputTemp.docx;

NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
System.out.println("Auth =" + auth);
String path = "smb: path" + fileName;
System.out.println("SMB PATH =" + path);

String output = "Downloads\\Projctnam\\src\\main\\resources\\templates\\";

DocxStamper stamper = new DocxStamper(new DocxStamperConfiguration());
InputStream inputStream = new FileInputStream(new File("template.docx"));
OutputStream out = new FileOutputStream(output+fileName);

SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write(out.toString().getBytes());

stamper.stamp(inputStream, variables, out);

sfos.close();
out.close();

这就是内容添加到文件的方式,

代码对我来说似乎很好。

sdnqo3pr

sdnqo3pr1#

所以,我找到了方法,现在一切正常

String user = "username:pwd";
String fileName = outputTemp.docx;

NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
System.out.println("Auth =" + auth);
String path = "smb: path" + fileName;
System.out.println("SMB PATH =" + path);

String output = "Downloads\\Projctnam\\src\\main\\resources\\templates\\";

DocxStamper stamper = new DocxStamper(new DocxStamperConfiguration());
InputStream inputStream = new FileInputStream(new File("template.docx"));
//OutputStream out = new FileOutputStream(output+fileName);

SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
//sfos.write(out.toString().getBytes());

stamper.stamp(inputStream, variables, sfos);

sfos.close();
out.close();

相关问题