技术标签: 导入导出
一.JAR
二.
1.使用office word创建word模板.wps创建可能会有问题
先插入一张图片占位置。本例导出后,应该是一张封面(会议记录册),后跟若干张图片。
2. 将word文件另存为Word xml格式
3.将xml文件重命名为.ftl文件,放入项目中
4.后台逻辑代码
@Override
public void exportWord(ZzshQueryVo zzshQueryVo, HttpServletResponse response, HttpServletRequest request) {
//查询需要导出的数据
List<LogbookVO> list = djZzshMapper.selectLogbookList(zzshQueryVo);
//导出
ExportWordUtil.exportWord(zzshQueryVo,list,request,response);
}
4.1ExportWordUtil
import com.zax.core.domain.vo.ImageVo;
import com.zax.core.domain.vo.LogbookVO;
import com.zax.core.domain.vo.ZzshQueryVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*poi导出word文档工具类
* @author qxc
* @date 2020/10/12
* @param
* @return
*/
public class ExportWordUtil {
private static Logger log = LoggerFactory.getLogger(ExportWordUtil.class);
//配置信息,代码本身写的还是很可读的,就不过多注解了
private static Configuration configuration = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
/**
* 功能描述:生成Word
* @param list 数据
* @author qxc
* @date 2020/10/12
*/
public static void exportWord(ZzshQueryVo zzshQueryVo, List<LogbookVO> list, HttpServletRequest request, HttpServletResponse response) {
Map map=new HashMap();
map.put("orgName",zzshQueryVo.getOrgName());
map.put("lifeTypeName",zzshQueryVo.getLifeTypeName());
map.put("beginTime",zzshQueryVo.getBeginTime());
List<ImageVo> urlList=new ArrayList<>();
for (int i=0;i<list.size();i++) {
LogbookVO logbookVO=list.get(i);
String imgUrls = logbookVO.getImgPath();
String[] splits = imgUrls.split(",");
for (int j=0;j<splits.length;j++ ) {
try {
//对象转换为Map
// Map data = JSONObject.parseObject(JSON.toJSONString(logbookVO), Map.class);
//获取文件的base64文件流
String imgPath = splits[j];
String str = imageToBase64ByOnline(imgPath);
//去除字节中的 空格换行符
str.replaceAll("\r\n|\r|\n", "");
ImageVo imageVo=new ImageVo();
imageVo.setBinUrl(str);
imageVo.setName("图片"+(i+1));
imageVo.setId(i+1);
//获取图片宽高
Map maps=getHeightAndWidth(str);
imageVo.setHeight(String.valueOf(maps.get("height")));
imageVo.setWidth(String.valueOf(maps.get("width")));
//图片类型
String type = imgPath.substring(imgPath.lastIndexOf(".") + 1);
imageVo.setType(type);
if(i<list.size()-1){
//最后一个会议之前,图片肯定要分页
imageVo.setNextPage("true");
}else{
//最后一个会议的最后一张图片不能分页,不然会多出一个空白页
if (j<splits.length-1 ){
imageVo.setNextPage("true");
}else{
imageVo.setNextPage("false");
}
}
urlList.add(imageVo);
} catch (Exception e) {
log.info("文件生成失败:" + e.getMessage());
e.printStackTrace();
}
}
}
map.put("imgUrl",urlList);
createWord(map, response,request);
}
/**
* 下载文件到浏览器
* @param request
* @param response
* @param filename 要下载的文件名
* @param file 需要下载的文件对象
* @throws IOException
*/
public static void downFile(HttpServletRequest request, HttpServletResponse response, String filename, File file) throws IOException {
// 文件存在才下载
if (file.exists()) {
OutputStream out = null;
FileInputStream in = null;
try {
// 1.读取要下载的内容
in = new FileInputStream(file);
// 2. 告诉浏览器下载的方式以及一些设置
// 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
String agent = request.getHeader("user-agent");
if (agent.contains("FireFox")) {
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
} else {
filename = URLEncoder.encode(filename, "UTF-8");
}
// 设置下载文件的mineType,告诉浏览器下载文件类型
String mineType = request.getServletContext().getMimeType(filename);
response.setContentType(mineType);
// 设置一个响应头,无论是否被浏览器解析,都下载
response.setHeader("Content-disposition", "attachment; filename=" + filename);
// 将要下载的文件内容通过输出流写到浏览器
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
}
/**
* 功能描述: 获取 base64文件流
* @param imgURL 文件路径
* @return java.lang.String
* @author qxc
* @date 2020/10/14
*/
public static String imageToBase64ByOnline(String imgURL) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(imgURL);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray());
}
/**
* 删除项目下生成的文件
* @param fileName
* @return boolean Returns "true" if all deletions were successful.
* If a deletion fails, the method stops attempting to
* delete and returns "false".
*/
public static boolean deleteDir(String fileName) {
File file = new File(fileName);
if (file.isFile() && file.exists()) {
file.delete();
} else {
return false;
}
return true;
}
/**
* 功能说明:创建word文档并返回给浏览器
* @param dataMap
* @param response
*/
public static void createWord(Map<String, Object> dataMap, HttpServletResponse response, HttpServletRequest request){
Template t=null;
try {
configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/download");
t =configuration.getTemplate("zzsh6.ftl");
} catch (IOException e) {
e.printStackTrace();
}
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(dataMap,t);
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = "会议记录册.doc";
try {
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
out = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
if(fin != null && out != null) {
try {
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
if(fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file != null) {file.delete();} // 删除临时文件
}
}
/**
* 功能说明: 创建doc文件
* @param dataMap 数据
* @param template 模板
* @return
*/
private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "test.doc";
File f = new File(name);
Template t = template;
try {
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return f;
}
/**
*功能描述:从base64文件流中获取图片属性
* @author qxc
* @date 2020/10/20
* @param data base64文件流
* @return java.util.Map
*/
public static Map getHeightAndWidth(String data) {
Map map=new HashMap();
try {
byte[] strBase64 = new BASE64Decoder().decodeBuffer(data);
InputStream is = new ByteArrayInputStream(strBase64);
BufferedImage image = ImageIO.read(is);
map.put("width",image.getWidth());
map.put("height",image.getHeight());
is.close();
}catch (Exception e){
e.printStackTrace();
}
return map;
}
}
5 ftl文件编辑:ftl文件总共有3部分要改
第一部分:
循环新增标签 ,一个图片一个,每个Relationship的Id不可重复,list imgUrl 是图片对象ImageVo集合,binUrl存的是Base64文件流
第二部分:
<w:body></w:body>标签中 把事先放入占位的图片换为循环展示
的id要和一致
第三部分:
找到事先放入的图片的字节流位置( pkg:binaryData中一大段字符串),替换为循环的
6:图片出不来原因:
可能性1:和的id不一致
可能性2:word保存ftl文件选择的版本不对
可能性3:获取的图片base64流中有/r/n等换行符,去除掉就可以
可能性4:wps建的模板有问题,建议使用office word建模板
可能性5:标签与变量间的空格(有时有空格,也会导致图片加载不出来)
文章浏览阅读6.3k次。 2005-09-05我的一个关于文件的程序 - [C语言]#includevoid main(){char ch;FILE* fp;if((fp=fopen("test.txt","r"))==NULL){printf("error");exit(1);}fseek(fp,0L,2);while((fseek(fp,-1L,1))!=-1){ch=fgetc(fp);pu_fseek(fp,0l,2)
文章浏览阅读674次。SQL查询前10条的方法为:select top X * from table_name--查询前X条记录,可以改成需要的数字,比如前10条。select top X * from table_name order by colum_name desc--按colum_name属性降序排序查询前X条记录,“order by” 后紧跟要排序的属性列名,其中desc表示降序,asc表示升序(默认也..._oracle怎么用语句设置查询结果数量
文章浏览阅读58次。讨论成员:罗凯旋、罗林杰、吴伟锋、黎文衷讨论完善APP,调试功能。转载于:https://www.cnblogs.com/383237360q/p/5011594.html
文章浏览阅读5.4k次。首先看你 favicon.ico 图标文件引入路径是否正确然后 看ico文件能否正常打开,这两个没问题的话,在地址栏直接输入你的域名 http://xxx.com/favicon.ico 注意 此刻可能还是 之前的ico图标 不要着急 刷新一下 试试 完美解决 清除程序缓存_win 软件开发 ico图标多久更新
文章浏览阅读2.1k次。Oracle归档日志删除我们都都知道在controlfile中记录着每一个archivelog的相关信息,当然们在OS下把这些物理文件delete掉后,在我们的controlfile中仍然记录着这些archivelog的信息,在oracle的OEM管理器中有可视化的日志展现出,当我们手工清除 archive目录下的文件后,这些记录并没有被我们从controlfile中清除掉,也就是or_rman 说明与资料档案库中在任何归档日志都不匹配
文章浏览阅读706次。命令提示符:[ root@localhost桌面] #[用户名@主机名 当前所在位置] #(超级用户) KaTeX parse error: Expected 'EOF', got '#' at position 25: …用户: #̲ su 用户名 //切… su密码:[ root@cml桌面] #临时提升为root权限:# sudo 命令..._命令提示符文件开头
文章浏览阅读152次。0x01 基本项目结构使用Android Studio创建的Android项目会划分成三个层级:project : settings.gradle定义了构建应用时包含了哪些模块;build.gradle定义了适用于项目中所有模块的构建配置module : 可以是一个app类型的module,对应生成apk应用;也可以是一个lib类型的module,对应生成aar包. 每个module中包含的bui..._android多个应用 gradle 怎么打包指定的应用
文章浏览阅读599次,点赞12次,收藏11次。前言:通常我们排序都需要创建一个函数实现排序,但当我们排完整型数组时,想要排字符串呢?那需要重新创建一个函数,完善它的功能,进而实现排字符串,这样非常繁琐,但是有一个函数可以帮我们实现传什么,排什么;qsort的传参:(1️⃣,2️⃣,3️⃣,4️⃣) (首元素地址,排序的元素个数,每个元素的大小,指向比较两个元素的函数的指针)1️⃣2️⃣3️⃣4️⃣的传参方法,下面介绍:…整型数组:......_qsort反向排序
文章浏览阅读355次。MVC绕过登陆界面验证时HttpContext.Current.User.Identity.Name取值为空问题解决方法_mvc 不验证登陆
文章浏览阅读7.6k次,点赞2次,收藏8次。1.分层领域模型规约: • DO( Data Object):与数据库表结构一一对应,通过DAO层向上传输数据源对象。 • DTO( Data Transfer Object):数据传输对象,Service或Manager向外传输的对象。 • BO( Business Object):业务对象。 由Service层输出的封装业务逻辑的对象。 • AO( Ap..._dto命名规范
文章浏览阅读91次。A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a pr..._pat甲级1015
文章浏览阅读1.5k次。ABAP接口之Http发送json报文abap 调用http 发送 json 测试函数SE11创建结构:zsmlscpnoticeSE37创建函数:zqb_test_http_fuc1FUNCTIONzqb_test_http_fuc1.*"----------------------------------------------------------------..._abap http 转换为json输出