java poi html转word并打包为zip下载
步骤:
1.html转word文件下载到本地
2.打包word为zip文件
3.弹出下载压缩包
全部后台代码:
package com.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @简介 下载文件相关:下载到本地-打包-弹出下载
* @作者 moyingmj
* @创建日期 2020/11/26 14:13
* @当前版本 v1.0
*/
public class DownLoadUtils {
/**
* @方法名 exportWord
* @简介 下载word到本地文件夹
* @param request
* @param response
* @param content html代码
* @param ModularName 下载到本地的路径,如:D盘
* @param filepath 路径
* @param projectName 下载到本地的文件夹名,如:\filePath
* @param uuid
* @param filename2 word文件名
* @返回值 com.alibaba.fastjson.JSONObject
* @作者 moyingmj
* @日期 2021/1/8 14:38
*/
public static JSONObject exportWord(HttpServletRequest request, HttpServletResponse response, String content, String ModularName, String filepath,
String projectName, String uuid, String filename2) throws Exception {
InputStream is = null;
FileOutputStream fileOut = null;
try {
byte b[] = content.getBytes("utf-8"); //这里是必须要设置编码的,不然导出中文就会乱码。
ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
//生成word
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
// 时间
Calendar calendar = Calendar.getInstance();
int year=calendar.get(calendar.YEAR);
int month=calendar.get(calendar.MONTH);
int day=calendar.get(calendar.DATE);
//文件夹路径
String path = ModularName+"/"+year+"/"+(month+1)+"/"+day+"/"+uuid;
File dir = new File(filepath+"/"+projectName+"/doc/"+path);
//判断是否存在文件夹 不存在新创建文件夹
if(!dir.exists()){
dir.mkdirs();
}
//处理一下文件名防止有中文
//String filename2 = name+"-"+phone+".doc"; //处理之后的文件名
//输出文件
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//设置word格式,注:此格式只能导出后缀名为.doc的文件,不能是.docx!!!
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment;filename=exportWord.doc");
FileOutputStream fileOutputStream = new FileOutputStream(filepath+"/"+projectName+"/doc/"+path+"/"+ filename2);
poifs.writeFilesystem(fileOutputStream);
fileOutputStream.close();
JSONObject object = new JSONObject();
object.put("path", path);//路径
object.put("filename", filename2);//word文件名
object.put("code", 0);//执行成功标识
return object;
}catch(Exception e){
//异常处理
log.error("文件导出错误", e);
e.printStackTrace();
return AjaxJsonUtils.error(e.getMessage());
}
}
/**
* @方法名 fileToZipAndUpload
* @简介 指定目录下的所有文件打包成zip文件并上传到本地
* @param dir 生成的压缩包的路径
* @param zipFileName 压缩包名
* @param request
* @param response
* @返回值 void
* @作者 moyingmj
* @日期 2021/1/8 14:45
*/
public static void fileToZipAndUpload(String dir,String zipFileName,HttpServletRequest request, HttpServletResponse response) {
String sourceFilePath =dir+"/";
log.info("待压缩文件所在目录:"+sourceFilePath);
File sourceFile = new File(sourceFilePath);
if(!sourceFile.exists()){
log.warn("压缩文件目录:"+sourceFilePath+"不存在");
}
File zipFile = new File(sourceFilePath+"/"+zipFileName+".zip");
if(zipFile.exists()){
log.warn(sourceFilePath+"目录下存在名字"+zipFileName+".zip的打包文件");
}
File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length < 1){
log.warn("待压缩的文件目录:"+sourceFilePath+"里面不存在文件,无需压缩");
}
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
try{
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024*6];
for (int i = 0; i < sourceFiles.length; i++) {
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis,1024*6);
int read = 0;
while((read=bis.read(bufs, 0, 1024*6)) != -1){
zos.write(bufs,0,read);
}
}
}catch (IOException e){
log.error("文件压缩异常 ",e);
try {
throw new Exception(e.getMessage());
} catch (Exception exception) {
exception.printStackTrace();
}
}finally {
try {
if(null != bis) bis.close();
if(null != fis) fis.close();
if(null != zos) zos.close();
if(null != fos) fos.close();
}catch (IOException e){
log.error("流关闭异常",e);
try {
throw new Exception(e.getMessage());
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
/**
* @方法名 downFile
* @简介 弹出下载本地已有zip文件
* @param path 路径
* @param fileName 压缩包文件名
* @param ContentType 可设置为null
* @param request
* @param response
* @返回值 java.lang.String
* @作者 moyingmj
* @日期 2021/1/8 14:46
*/
public static String downFile(String path,String fileName,String ContentType,HttpServletRequest request, HttpServletResponse response)
throws IOException {
if (ContentType == null || ContentType.equals(""))
ContentType = "application/octet-stream";
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
filename = fileName + "."+ext;
// 获取文件读取刘
InputStream fis = new FileInputStream(path);
// 获取response;
//HttpServletResponse response = ServletActionContext.getResponse();
// 响应类型
response.setContentType(ContentType);
// 获取写流
ServletOutputStream os = response.getOutputStream();
;
// 设置下载文件名
response.addHeader("Content-Disposition", "attachment;filename="
+ java.net.URLEncoder.encode(filename, "utf-8"));
// 设置下载文件大小
response.addHeader("Content-Length", "" + file.length());
int i = 0;
byte[] b = new byte[1024 * 8];
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
return null;
}
}