java将html转为word导出(富⽂本内容导出word)
业务:
将富⽂本内容取出⽣成本地word⽂件
参考百度的⽅法
word本⾝是可以识别html标签,所以通过poi写⼊html内容即可
import com.util.WordUtil;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysAnnouncementController {
@PostMapping(value = "/exportAccidentExampleWord")
public void exportAccidentExampleWord(HttpServletRequest request, HttpServletResponse response) throws Exception {
String s = "<p><strong>第⼀⾏要加粗</strong></p>\n" +
"<p><em><strong>第⼆⾏要倾斜</strong></em></p>\n" +
"<p style=\"text-align: center;\"><em><strong>第三⾏要居中</strong></em></p>";
StringBuffer sbf = new StringBuffer();
sbf.append("<html " +
"xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"schemas.microsoft/office/2004/12/omml\" xmlns=\"w ">");//缺失的⾸标签
sbf.append("<head>" +
"<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedCo "</head>");//将版式从web版式改成页⾯试图
sbf.append("<body>");//缺失的⾸标签
sbf.append(s);//富⽂本内容
sbf.append("</body></html>");//缺失的尾标签
try{
}catch (Exception e){
System.out.Message());
}
}
}
⼯具类
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
public class WordUtil {
public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws Exception {
byte[] b = Bytes("GBK"); //这⾥是必须要设置编码的,不然导出中⽂就会乱码。
ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = Root();
DocumentEntry documentEntry = ateDocument("WordDocument", bais); //该步骤不可省略,否则会出现乱码。
//输出⽂件
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword");//导出word格式
response.addHeader("Content-Disposition", "attachment;filename=" +
new Bytes("GB2312"),"iso8859-1") + ".doc");
ServletOutputStream ostream = OutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
poifs.close();
}
public static void downloadWord( byte[] b, OutputStream out)
throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
try {
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = Root();
DocumentEntry documentEntry = ateDocument("WordDocument", bais);
poifs.writeFilesystem(out);
bais.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}finally {
if(bais!=null){bais.close();}
if(out!=null) {out.flush();out.close();}
}
}
pdf转html}
发布评论