java生成带html样式的word文件

参考:http://blog.csdn.net/xiexl/article/details/6652230

最近在项目中需要将通过富文本编辑器处理过的文字转换为Word,查了很久,大家通常的解决办法是使用Jacob或POI等组件直接生成Word,但是都无法将富文本编辑器处理过的文字保留样式并保存为Word,最终以失败而告终,无奈只有自己研究Word的格式转换;

分析了转换过程,总体分两个步骤:

1、实现富文本中样式代码的分离;

2、保留CSS样式;

其实以上两个步骤是相互矛盾的处理过程,无法通过Jacob或POI组件加正则表达式过滤解决,于是进行了以下步骤的实验:

1、首先创建了一个空白word文档,格式(office 2003格式或office 2007格式)不限;

2、将word格式保存为html格式,通过Edit Plus打开,发现代码中使用了office的命名空间,同时使用了office命名空间的标签定义了CSS样式,自己测试了一下,将生成的html文件头和尾拷贝出来:代码如下:

xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">

<!-- 富文本代码区 --&gt

以上HTML头是office的命名空间定义。

3、将使用富文本代码粘贴到红色标识的<!-- 富文本代码区 --&gt中,并以doc或docx格式保存文件;

4、大功告成,打开文件时,Word将会以“Web版视图”完美显示了富文本样式,成功解决了富文本代码中样式代码,并同时保留了格式;

目前研究的仅能保存文字,未处理有图片的代码,朋友们可以再研究一下带图片的富文本代码的转换;

[@more@]

根据上面的,现在我们只需要在服务器建一个.doc的文件,然后再把我们的带html样式的文本写到这个文件中,再下载到客户端就可以了

下面实现的代码,首先写一个工具类用来生成word文件

package net.uni.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
* 处理内容:生成带html样式的word文档
* @version: 1.0
* @see:net.uni.util.JavaWordUtil.java
* @date:2012-7-5
* @author:孙伟
*/
public class JavaWordUtil {

private JavaWordUtil(){}

private static String CHARSET = "gbk";//编码格式

private static String PATH = "E:uploadword";//本地测试路径

//private static String PATH = "/home/upload/base/word/";//服务器文件存放路径

/**
* @param fileName
* @param content
* @return
* @方法说明 生成word文档,如果返回null,则表示生成失败
* @date 2012-7-5
* @author 孙伟
*/
public static String createWordFile(String fileName,String content){
OutputStreamWriter os = null;
FileOutputStream fos = null;
try{
if(fileName.indexOf(".doc")>-1){
fileName = fileName.substring(0, fileName.length()-4);
}

File file = new File(PATH);

//如果目录不存在就创建
if (!(file.exists() && file.isDirectory())) {
file.mkdirs();
}

fileName = PATH + "" + fileName + "-" +System.currentTimeMillis() + ".doc";

//创建文件
File targetFile = new File(fileName);
if(!targetFile.exists()){
targetFile.createNewFile();
}
fos = new FileOutputStream(fileName);
os = new OutputStreamWriter(fos,CHARSET);
os.append(content.toString());
os.flush();
return fileName;
}catch(Exception e){
return null;
}finally{
try{
os.close();
fos.close();
}catch(Exception e){
return null;
}
}
}
}

然后就是struts2配置下载文件的步骤:

action里定义两个属性

private String conFileName;//生成的合同模板的word文件名称
private InputStream inputStream;//下载商务合同模板流

注意这两个属性的文件名称的get方法有些不同,为了处理文件名中文乱码的问题

public String getConFileName() {
String downFileName = conFileName;
try {
downFileName = new String(downFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downFileName;
}

然后是action的主方法

/**
* @return
* @throws ActionException
* @方法说明 下载商务合同模板
* @date 2012-7-5
* @author 孙伟
*/
public String downLoadCustCon() throws ActionException{
try{
StringBuffer content = new StringBuffer();

Long conId = this.cscustcon.getId();
this.cscustcon = this.csCustConService.findCsCustConbyID(conId);
List conHead = csCustConService.findCustConHeadInfo(conId);
//合同头信息
for(String s : conHead){
content.append(s);
}
//合同条款已经条款的内容
List> conItem = csCustConService.findCustConContent(conId);
for(List ls : conItem){
for(String sl : ls){
content.append(sl);
}
}

String filePath = JavaWordUtil.createWordFile(cscustcon.getContName(), content.toString());

if(filePath==null||filePath.trim().equals("")) throw new ActionException("合同模板下载失败");

File file = new File(filePath);

if(!file.exists()){
throw new ActionException("文件不存在!");
}

conFileName = cscustcon.getContName()+".doc";

inputStream = new FileInputStream(file);

}catch(Exception e){
throw new ActionException("下载商务合同模板失败",e);
}
return SUCCESS;
}

struts.xml文件的配置:

<!--商务合同下载--&gt



inputStream

application/octet-stream;charset=ISO8859-1

attachment;filename=${conFileName}
2048

页面的写法:

window.location.href=getBasePath()+"/cs/downLoadCustCon.action?cscustcon.id="+conId+"&itemContent="+$("#itemContentId").val();

到此下面带html样式的word文件就完成了

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25261409/viewspace-1058739/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/25261409/viewspace-1058739/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 Apache POI 库来生成有分页和目录的 Word 文档。以下是一个简单的示例代码: ```java import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.*; public class GenerateWordDocument { public static void main(String[] args) throws Exception { // 创建 Word 文档 XWPFDocument doc = new XWPFDocument(); // 添加标题 XWPFParagraph title = doc.createParagraph(); title.setAlignment(ParagraphAlignment.CENTER); XWPFRun titleRun = title.createRun(); titleRun.setText("这是一个标题"); titleRun.setBold(true); titleRun.setFontSize(18); // 添加分页 XWPFParagraph pageBreak = doc.createParagraph(); pageBreak.setPageBreak(true); // 添加目录 XWPFParagraph toc = doc.createParagraph(); toc.setAlignment(ParagraphAlignment.CENTER); XWPFRun tocRun = toc.createRun(); tocRun.setText("目录"); tocRun.setBold(true); tocRun.setFontSize(16); XWPFParagraph chapter1 = doc.createParagraph(); chapter1.setStyle("Heading1"); XWPFRun chapter1Run = chapter1.createRun(); chapter1Run.setText("章节 1"); XWPFParagraph chapter1Content = doc.createParagraph(); chapter1Content.setAlignment(ParagraphAlignment.LEFT); XWPFRun chapter1ContentRun = chapter1Content.createRun(); chapter1ContentRun.setText("这是章节 1 的内容"); XWPFParagraph chapter2 = doc.createParagraph(); chapter2.setStyle("Heading1"); XWPFRun chapter2Run = chapter2.createRun(); chapter2Run.setText("章节 2"); XWPFParagraph chapter2Content = doc.createParagraph(); chapter2Content.setAlignment(ParagraphAlignment.LEFT); XWPFRun chapter2ContentRun = chapter2Content.createRun(); chapter2ContentRun.setText("这是章节 2 的内容"); // 保存 Word 文档 FileOutputStream out = new FileOutputStream("example.docx"); doc.write(out); out.close(); doc.close(); } } ``` 在此示例中,我们使用 `XWPFDocument` 类创建了一个新的 Word 文档,使用 `createParagraph()` 方法和 `createRun()` 方法添加了标题、分页和目录。我们还使用 `setStyle()` 方法设置了章节标题的样式。最后,使用 `FileOutputStream` 类将文档保存到本地磁盘。您可以根据需要进行修改和扩展此示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值