简体   繁体   English

如何在java中手动创建doc/docx文件

[英]How to create doc/docx file manually in java

I create a docx file with pure string in java.我在java中用纯字符串创建了一个docx文件。 when I send email the docx file to my phone, file can not be opened properly.当我将 docx 文件通过电子邮件发送到我的手机时,文件无法正常打开。

My java code is:我的Java代码是:

// creating a docx file
File wordFile = new File("myDocFile.docx");
wordFile.createNewFile();

 String title   = "my document title here";
 String content = "my document content here";

 // docx file content with Html
String fileStr = "<!DOCTYPE html><meta http-equiv=\"content-type\" " +
" content=\"application/msword; charset=UTF-8\">" + 
"<h1 style='text-align:center;'>" + title+ "</h1>" + content;

// writing fileStr in to docx file.
   Files.write(wordFile.toPath(), fileStr.getBytes("UTF-8"),
   StandardOpenOption.TRUNCATE_EXISTING);

My docx file that created is not be opened in smart phone.我创建的 docx 文件无法在智能手机中打开。 How can I do docx to be read in smart phone?如何在智能手机中读取 docx?

Two simple misconceptions here:这里有两个简单的误解:

  • sure, docx has open XML content, but still you shouldn't try to create such files manually , use a reasonable library, such as apache POI .当然,docx 具有开放的 XML内容,但您仍然不应该尝试手动创建此类文件,而应使用合理的库,例如apache POI Seriously: you start with a simple "body", but anything that is useful in the real world grows.说真的:你从一个简单的“身体”开始,但在现实世界中任何有用的东西都会增长。 Your requirements will turn more complex quickly, and then you spend a lot of time re-implementing what such libraries do for you.您的需求将很快变得更加复杂,然后您会花费大量时间重新实现这些库为您所做的事情。 Re-inventing wheels is costly, especially given the fact that your wheel will really suck compared to any mature library for that job.重新发明轮子是昂贵的,特别是考虑到与该工作的任何成熟库相比,你的轮子真的很糟糕。
  • How can I do docx to be read in every smart phone?我如何才能在每部智能手机中阅读 docx? You can't.你不能。 You have no control over "every" smart phone in the world, thus you can't enforce that the person receiving your docx is able to view it.无法控制世界上的“每一部”智能手机,因此您无法强制接收您的 docx 的人能够查看它。

Long story short: your whole approach looks "broken by design".长话短说:你的整个方法看起来“被设计破坏了”。 Many people really don't like being send "office" files (for good security reasons that is).许多人真的不喜欢被发送“办公室”文件(出于良好的安全原因)。

So, the real answer is: step back, and evaluate what kind of information you want to "send out", and then figure ways that actually work for all your users.所以,真正的答案是:退一步,并评估样的信息要“送出去”的,然后图的方式,对所有用户实际工作

When you are already sending them emails, consider putting some good old plain text into them.当您已经向他们发送电子邮件时,请考虑将一些好的旧纯文本放入其中。 In general: sending emails with files attached to them is a great way of annoying your users.一般而言:发送附有文件的电子邮件是一种惹恼用户的方法。 It should be your last resort, not your first.这应该是你最后的手段,而不是你的第一个手段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM