JAVA实现PDF和EXCEL生成和数据动态插入以及导出
Java项目开发
共 10067字,需浏览 21分钟
·
2021-03-13 00:48
点击上方 java项目开发 ,选择 星标 公众号
重磅资讯,干货,第一时间送达
一、序言
二、Java 实现 PDF 的生成和数据动态插入、导出功能
1、第一步:PDF 制作模板
2、代码的编写(假定我们实体类什么的都已经编写完成、数据通过前端传入获取、模板位置在 E 盘根目录下名字为:车辆维修审批单. pdf)
导入 jar 包:
<!-- PDF导出-->
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
实现生成 PDF、数据插入、导出
public String exportPdf( GwclwxsqBean gwclwxsqBean , HttpServletResponse response) throws UnsupportedEncodingException {
// 1.指定解析器
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
String file;
String path="e:/";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName="
+ URLEncoder.encode(filename, "UTF-8"));
OutputStream os = null;
PdfStamper ps = null;
PdfReader reader = null;
try {
os = response.getOutputStream();
// 2 读入pdf表单
reader = new PdfReader(path+ "/"+filename);
// 3 根据表单生成一个新的pdf
ps = new PdfStamper(reader, os);
// 4 获取pdf表单
AcroFields form = ps.getAcroFields();
// 5给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示
BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
form.addSubstitutionFont(bf);
// 6查询数据================================================
Map<String, String> data = new HashMap<String, String>();
data.put("commitTime", gwclwxsqBean.getCommitTime());
data.put("driver", gwclwxsqBean.getDriver());
data.put("carId", gwclwxsqBean.getCarId());
data.put("carType", gwclwxsqBean.getCarType());
data.put("repairAddress", gwclwxsqBean.getRepairAddress());
data.put("repairCost",gwclwxsqBean.getRepairCost());
data.put("project", gwclwxsqBean.getProject());
data.put("fwbzzxfzrYj", gwclwxsqBean.getFwbzzxfzrYj());
data.put("fgldspYj", gwclwxsqBean.getFgldspYj());
data.put("remarks", gwclwxsqBean.getRemarks());
// 7遍历data 给pdf表单表格赋值
for (String key : data.keySet()) {
form.setField(key,data.get(key).toString());
}
ps.setFormFlattening(true);
log.info("*******************PDF导出成功***********************");
} catch (Exception e) { log.error("*******************PDF导出失败***********************");
e.printStackTrace();
} finally {
try {
ps.close();
reader.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
3. 测试
二、Java 实现 Excel 生成和数据插入、导出
1. 表头对应实体类 ExportYqfkdj.java:
import lombok.Data;
/**
* description:
* @author: zhouhong
* @version: V1.0.0
* @date: 2021年1月14日 下午3:05:54
*/
public class ExportYqfkdj {
/**
* 序号
*/
private Integer xuhao;
/**
* 姓名
*/
private String xingming;
/**
* 证件号码
*/
private String zjhm;
/**
* 联系电话
*/
private String lxdh;
/**
* 申请人工作单位
*/
private String sqrGzdw;
/**
* 是否接触过疑似病例
*/
private String sfjcgysbl;
/**
* 当前是否与居家隔离人员同住
*/
private String sfyjjglrytz;
/**
* 当前状态
*/
private String dqzt;
/**
* 当前健康状态
*/
private String dqjkzt;
/**
* 当前体温
*/
private String dqtw;
/**
* 当前所在地址
*/
private String dqszdz;
/**
* 当前居住地址
*/
private String dqjzdz;
/**
* 提交时间
* */
private String tjsj;
}
b.Service 层
/**
* 导出
* @param yqfkdjBean
* @author zhouhong
* @return
* @throws Exception
*/
@Transactional(rollbackFor = { Exception.class })
public DataResult exporYqfkdj(YqfkdjBean yqfkdjBean) throws Exception {
DataResult result = new DataResult();
List<ExportYqfkdj> list = new ArrayList<ExportYqfkdj>();
try {
/* 查询导出信息 */
result = getYqfkMhCXQuery(yqfkdjBean);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
for (int i = 0; i < result.getTotalcount(); i++) {
ExportYqfkdj dmKhfwdcDtjlZxDto = new ExportYqfkdj();
dmKhfwdcDtjlZxDto = ObjectUtil.parsePojo(result.getResults().get(i), ExportYqfkdj.class);
dmKhfwdcDtjlZxDto.setXuhao(i + 1);
list.add(dmKhfwdcDtjlZxDto);
}
String filepath = "D:/疫情防控信息" + df.format(new Date()) + ".xlsx";
if (System.getProperty(YqfkdjUtils.Wjdz.NAME).toLowerCase().startsWith(YqfkdjUtils.Wjdz.LI)
|| System.getProperty(YqfkdjUtils.Wjdz.NAME).toLowerCase().startsWith(YqfkdjUtils.Wjdz.LIN)) {
filepath = "/home/Tomcat/temp/" + df.format(new Date()) + ".xlsx";
}
EasyExcel.write(filepath, ExportYqfkdj.class).head(head()).sheet().doWrite(list);
result.setResults(list);
result.setSuccess(true);
result.setMsg(filepath);
} catch (Exception e) {
result.setSuccess(false);
result.setMsg(YqfkdjUtils.Cytx.DCSB);
e.printStackTrace();
throw e;
}
return result;
}
/**
* 疫情防控信息导出表头
* @author zhouhong
* @return List<List<String>>
*/
private List<List<String>> head() {
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add("序号");
List<String> head1 = new ArrayList<String>();
head1.add("姓名");
List<String> head2 = new ArrayList<String>();
head2.add("证件号码");
List<String> head3 = new ArrayList<String>();
head3.add("联系电话");
List<String> head4 = new ArrayList<String>();
head4.add("工作所在单位");
List<String> head5 = new ArrayList<String>();
head5.add("是否接触疑似病例");
List<String> head6 = new ArrayList<String>();
head6.add("是否与隔离人员同住");
List<String> head7 = new ArrayList<String>();
head7.add("当前状态");
List<String> head8 = new ArrayList<String>();
head8.add("当前健康状态");
List<String> head9 = new ArrayList<String>();
head9.add("体温(°C)");
List<String> head10 = new ArrayList<String>();
head10.add("当前所在地址");
List<String> head11 = new ArrayList<String>();
head11.add("当前居住地址");
List<String> head12 = new ArrayList<String>();
head12.add("提交时间");
list.add(head0);
list.add(head1);
list.add(head2);
list.add(head3);
list.add(head4);
list.add(head5);
list.add(head6);
list.add(head7);
list.add(head8);
list.add(head9);
list.add(head10);
list.add(head11);
list.add(head12);
return list;
}
c.Controller 层
@RegisterToSMP(serviceDisplay = "疫情防控查询导出")
@RequestMapping(value = "/DM/yqfkdj/gr/yqfkdjdc$m=export.service", method = RequestMethod.POST)
public void exportKhfxxx(@RequestBody YqfkdjBean yqfkdjBean, HttpServletResponse resp) throws Exception {
DataResult result = new DataResult();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
result = yqfkdjService.exporYqfkdj(yqfkdjBean);
String filepath = result.getMsg().replace("\"", "");
File file = new File(filepath);
String filename = "疫情防控信息" + df.format(new Date()) + ".xlsx";
InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
resp.reset();
resp.setHeader("Content-Disposition",
"attachment;file)));
resp.setHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(resp.getOutputStream());
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// 输出文件
os.write(buffer);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
log.info(YqfkdjUtils.Cytx.DCSB);
throw e;
}
}
d. 测试
怎么接私货?这个渠道你100%有用!请收藏!
评论