打印,excel、pdf导出及导入
@TOC
前言
一、引入依赖
1.引入页面依赖
2.引入maven依赖
org.apache.poi
poi
3.12
cn.afterturn
easypoi-base
3.0.1
cn.afterturn
easypoi-web
3.0.1
cn.afterturn
easypoi-annotation
3.0.1
com.itextpdf
font-asian
7.0.4
test
com.itextpdf
kernel
7.0.4
com.itextpdf
io
7.0.4
com.itextpdf
layout
7.0.4
com.itextpdf
forms
7.0.4
com.itextpdf
pdfa
7.0.4
com.itextpdf
pdftest
7.0.4
二、elementui页面(含LODOP自动A4打印)
三、控制器及接口
1.单表多sheet
@RequestMapping("/exportExcel")
@ResponseBody
public void exportExcel(HttpServletResponse response, reportParam params) {
try {
List
2.批量多表多sheet
@RequestMapping("/monthUserExportExcelZip")
@ResponseBody
public void exportExcelZip(HttpServletResponse response, ReportParam params) {
try {
String fileName = "送货单-" + new SimpleDateFormat("yyyyMMdd").format(new Date());
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8") + ".zip");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
if (params.getInvoiceId() != null) {
List list = reportService.getOrderGroup(params);
list.forEach(e -> {
params.setCompanyId(e.getCompanyId());
params.setAddrId(e.getAddrId());
List> lists = this.exportExcelSheet(params);
if(!lists.isEmpty()){
MyExcelExportUtil.exportExcel(lists,e.getCompanyName() + "-" + e.getStreet(),ExcelType.HSSF,zipOut);
}
});
}
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description 单表多sheet批量导出
* @Param [list, headTitle, type, zipOS]
**/
public static ZipOutputStream exportExcel(List> list, String headTitle,ExcelType type, ZipOutputStream zipOS) {
try {
Workbook workbook = ExcelExportUtil.exportExcel(list,type);
String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
ZipEntry zipEntry = new ZipEntry(fileName+".xls");
zipOS.putNextEntry(zipEntry);
workbook.write(zipOS);
return zipOS;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3.PDF
@RequestMapping("/exportPDF")
@ResponseBody
public Result exportPDF(HttpServletResponse response, MonthUserReportParam params) {
try {
String filePath = reportService.getPDF(params);
if (StringUtils.isBlank(filePath)) {
return Results.error("未知错误,请联系管理员");
}
File file = new File(filePath);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式-文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
logger.error("导出送货单PDF失败!params:" + params.toString(), e);
}
return Results.error("导出送货单失败");
}
public String getPDF(ReportParam params) {
// params.setInvoiceId("0");
String companyName = "";
String cachetImageUrl = null; // 公章图片地址
Calendar calendar = Calendar.getInstance();
List deliveryNoteAllDtos = new ArrayList();
try {
Date btimeDate = params.getTime()[0];
Date enDate = params.getTime()[1];
int days = DateUtil.differentDays(btimeDate, enDate);
for (int i = 0; i <= days; i++) {
DeliveryDto deliveryDto = new DeliveryDto();
calendar.setTime(btimeDate);
if (i == 0) {
calendar.add(calendar.DATE, 0);
} else {
calendar.add(calendar.DATE, 1);
}
btimeDate = calendar.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
params.setOrderTime(df.format(btimeDate));
if (params.getOrderTime() == null || params.getOrderTime().equals("")) {
params.setOrderTime(sdf_day.format(new Date()));
}
if (params.getCompanyId() != null && !params.getCompanyId().equals("")) {
Date date = sdf_day.parse(params.getOrderTime());
params.setOrderTime(df.format(date));
List dtos = this.listReport(params);
List list = this.CompanyMessage(params);
CompanyMessageDto companyMessageDto = new CompanyMessageDto();
if (list.size() > 0) {
companyMessageDto = list.get(0);
deliveryDto.setAddress(companyMessageDto.getCompanyAddress());
deliveryDto.setBucketQuantity(companyMessageDto.getBucketQuantity());
deliveryDto.setCompanyName(companyMessageDto.getCompanyName());
deliveryDto.setCreateTime(companyMessageDto.getOrderTime());
deliveryDto.setPlateQuantity(companyMessageDto.getPlateQuantity());
deliveryDto.setReceiverName(companyMessageDto.getReceiverName());
deliveryDto.setTelephone(companyMessageDto.getTelephone());
companyName = companyMessageDto.getCompanyName();
if(params.getInvoiceId().equals("2")){
cachetImageUrl = companyMessageDto.getImageUrl();
}else{
cachetImageUrl = companyMessageDto.getTaxImageUrl();
}
}
if (dtos != null && dtos.size() > 0) {
ReportDto reportDto = new ReportDto();
reportDto.setProductName("合计");
BigDecimal itemAmount = EntityConvertor.count(dtos, ReportDto::getAllmoney);
reportDto.setAllmoney(itemAmount);
dtos.add(reportDto);
}
deliveryDto.setList(dtos);
}
deliveryDtos.add(deliveryDto);
}
// 添加减退
List orderAlterList = this.orderExcelAll(params);
// 添加补货
List orderAddList = this.orderAddExcelAll(params);
if(deliveryDtos.size()<=0 && orderAddList.isEmpty() && orderAddList.isEmpty()) {
logger.error("导出送货单数据为0");
return "";
}
return this.createPdf(deliveryDtos,orderAlterList,orderAddList,companyName, params.getEmail(),cachetImageUrl);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "";
}
}
/*
* 送货单PDF
*/
public String createPdf(List dtos,List orderAlterList,List orderAddList,String companyName, String email,String cachetImageUrl) {
Document document = null;
// logger.error("***************开始进入生产PDF文件");
try {
String fileName = companyName + UUID.randomUUID().toString().replace("-", "") + ".pdf";
if (StringUtils.isBlank(pdfPath) ) {
pdfPath = "C://songhuodan//";
}
String file = pdfPath + fileName;
PdfWriter writer = new PdfWriter(file);
PdfDocument pdf = new PdfDocument(writer);
String fontPath = pdfFontPath + "STFANGSO.TTF";
pdfFont = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);
document = new Document(pdf);
boolean isNull = true;
for (DeliveryDto deliveryDto : dtos) {
if (deliveryDto.getList().size() <= 0) {
continue;
}
isNull = false;
Paragraph title = new Paragraph(" 商 城 ").setFont(pdfFont).setFontSize(14)
.setTextAlignment(TextAlignment.CENTER).setBold();
LocalDate date = LocalDate.parse(deliveryNoteAllDto.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Paragraph p = new Paragraph("企业名称: " + deliveryDto.getCompanyName() + " 日期: "
+ date.plusDays(1).toString()).setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
Paragraph addr = new Paragraph("地址: " + deliveryDto.getAddress()).setFont(pdfFont)
.setWidthPercent(90).setTextAlignment(TextAlignment.LEFT);
Paragraph pepole = new Paragraph("联系人: " + deliveryDto.getReceiverName()).setFont(pdfFont)
.setTextAlignment(TextAlignment.LEFT);
Paragraph tel = new Paragraph("联系电话: " + deliveryDto.getTelephone()).setFont(pdfFont)
.setTextAlignment(TextAlignment.LEFT);
Paragraph remark1 = new Paragraph("温馨提示: ").setFont(pdfFont)
.setTextAlignment(TextAlignment.LEFT);
Paragraph remark2 = new Paragraph(
"\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a02、误差; ")
.setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
Paragraph remark3 = new Paragraph(
"\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a03、联系客服,感谢您的配合;")
.setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
Paragraph remark4 = new Paragraph(
"\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a04、请客户保存好")
.setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
Paragraph remark5 = new Paragraph(
"\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0送_________框;回_________框;存_________框 ")
.setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
// 定义表格
Table table = new Table(new float[] { 50f, 150f, 120f, 60f, 60f, 80f });
table.setWidth(UnitValue.createPercentValue(100));
// 自定义的封装表格数据
formatData(table, deliveryNoteAllDto.getList());
document.add(title);
document.add(p);
document.add(addr);
document.add(pepole);
document.add(tel);
document.add(table);
document.add(remark1);
document.add(remark2);
document.add(remark3);
document.add(remark4);
document.add(remark5);
// 为pdf添加公章图片水印
int pageNum = pdf.getNumberOfPages();
if(pageNum==1) {
this.watermarkImagePdf(pdf,cachetImageUrl,pageNum);
}
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
int pageNum1 = pdf.getNumberOfPages();
if(pageNum1<=dtos.size() && pageNum1 != 1){
this.watermarkImagePdf(pdf,cachetImageUrl,pageNum1);
}
}
// 添加减退
if(!orderAlterList.isEmpty()){
Paragraph title1 = new Paragraph("明 细").setFont(pdfFont).setFontSize(13)
.setTextAlignment(TextAlignment.CENTER).setBold();
Table table1 = new Table(new float[] { 50f, 105f, 70f, 95f, 100f, 75f, 65f, 80f, 85f });
formatAlterData(table1,orderAlterList);
document.add(title1);
document.add(table1);
}
// 添加补货
if(!orderAddList.isEmpty()){
Paragraph title2 = new Paragraph("明 细").setFont(pdfFont).setFontSize(13)
.setTextAlignment(TextAlignment.CENTER).setBold();
Table table2 = new Table(new float[] { 50f, 105f, 70f, 125f, 130f, 80f });
formatAddData(table2,orderAddList);
document.add(title2);
document.add(table2);
}
if(isNull){
document.add(new Paragraph("无匹配数据").setFont(pdfFont).setFontSize(14).setTextAlignment(TextAlignment.CENTER).setBold());
}
document.close();
String addressee = email;
if (StringUtils.isAllBlank(addressee)) {
addressee = "123456789@163.com";
} else {
/** 邮件标题 **/
String subject = "送货单";
/** 邮件正文 **/
String content = "感谢您";
/** 邮件文档 **/
logger.error(addressee+"开始发送邮件");
EmailHelp.sendEmail(file, addressee, content, subject);
logger.error(addressee+"结束发送邮件");
}
logger.error("***************PDF文件生成完毕");
return file;
} catch (Exception e) {
logger.error("*********生成的PDF报的错误***********"+e.getMessage());
e.printStackTrace();
}
return "";
}
4.批量导入excel
@RequestMapping("/uploadExcel")
@ResponseBody
public Result uploadImage(MultipartFile file) {
if(file!=null) {
//检查文件
try {
MyExcelExportUtil.checkFile(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Results.error("只能导入Excel格式文件");
}
List excelImportDtos = MyExcelExportUtil.importExcel(file, 1, 1, ExcelImportDto.class);
List list = new ArrayList();
if(excelImportDtos.size()>0) {
for (ExcelImportDto excelImportDto : excelImportDtos) {
if(excelImportDto!=null&&excelImportDto.getQuantity()!=null) {
int quantity = Integer.parseInt(excelImportDto.getQuantity());
if(quantity>0) {
if(excelImportDto.getTotalPrice()!=null) {
double AmountMoney = Double.parseDouble(excelImportDto.getTotalPrice());
double price = AmountMoney /quantity;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
excelImportDto.setPrice(nf.format(price));
excelImportDto.setId(UUID.randomUUID().toString());
list.add(excelImportDto);
}
}
}
}
}
return Results.listResult(list);
}
else {
return Results.error("请选择文件");
}
}
public static List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw e;
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* Excel 导入 数据源IO流,不返回校验结果 导入 字段类型 Integer,Long,Double,Date,String,Boolean
*
* @param inputstream
* @param pojoClass
* @param params
* @return
* @throws Exception
*/
public static List importExcel(InputStream inputstream, Class> pojoClass,
ImportParams params) throws Exception {
return new ExcelImportServer().importExcelByIs(inputstream, pojoClass, params).getList();
}
随心所往,看见未来。Follow your heart,see night!
欢迎点赞、关注、留言,一起学习、交流!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~