效果图:(涉及客户隐私打码)
以前觉得excle里面图片是浮动的,不是针对某一栏的,后来上网还真的有相应的插件实现,POI!
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
我的工具类代码:
package com.jeesite.modules.py.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.jeesite.modules.py.entity.PyNarcotics;
import com.jeesite.common.config.Global;
import com.jeesite.common.io.FileUtils;
@Component
public class ExportUtils {
@Value("${file.baseDir}")
private static String dir;
/**
* 导出Excel(带图片)
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,List<PyNarcotics> list, HSSFWorkbook wb){
// HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
row.setHeight((short) 500);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//声明列对象
HSSFCell cell = null;
//列宽
int[] wids={4000,4000,7000,6000,6000,7000,8000,8000,10000,4000};
//创建标题
for(int i=0;i<title.length;i++){
sheet.setColumnWidth(i, wids[i]);
cell = row.createCell(i);
cell.setCellValue(title[i]);
HSSFFont font = wb.createFont();
font.setFontName("Arial");
font.setColor(HSSFColor.WHITE.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short) 12);//设置字体大小
style.setFont(font);
cell.setCellStyle(style);
}
BufferedImage bufferImg = null;//图片
try {
//创建内容
HSSFCellStyle styleCon = wb.createCellStyle();
styleCon.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
styleCon.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// for(int i=0;i<list.size();i++){
for(int j=list.size(),i=0;j>0;j--,i++){
row = sheet.createRow(i + 1);
row.setHeight((short) 1000);
PyNarcotics pyNarcotics = list.get(j-1);
//将内容按顺序赋给对应的列对象
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
String[] arr = null ;
String imgStr = pyNarcotics.getPhoto();
if(imgStr != null && !imgStr.equals("")){
arr = imgStr.split(",");
String baseImage = Global.getConfig("file.baseDir")+arr[0];
//判断图片是否存在
if (new File(baseImage).exists()) {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(baseImage));
ImageIO.write(bufferImg, FileUtils.getFileExtension(pyNarcotics.getPhoto()), byteArrayOut);
//图片一导出到单元格bi中
HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 250,
(short) 1, i+1, (short) 1, i+1);
patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
}
}
/*//导出多张照片的情况
for(int j=0;j<arr.length;j++){
sheet.setColumnWidth(10+j-1, 4000);
String baseImage = Global.getConfig("file.baseDir")+arr[j];
//判断图片是否存在
if (new File(baseImage).exists()) {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(baseImage));
ImageIO.write(bufferImg, FileUtils.getFileExtension(pyNarcotics.getPhoto()), byteArrayOut);
//图片一导出到单元格j11中
HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 250,
(short) (10+j-1), i+1, (short) (10+j-1), i+1);
patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
}
}*/
cell = row.createCell(0);cell.setCellValue(pyNarcotics.getName());
cell.setCellStyle(styleCon);
cell = row.createCell(2);cell.setCellValue(pyNarcotics.getIdCard());
cell.setCellStyle(styleCon);
cell = row.createCell(3);cell.setCellValue(pyNarcotics.getPhone());
cell.setCellStyle(styleCon);
cell = row.createCell(4);cell.setCellValue(pyNarcotics.getWeChat());
cell.setCellStyle(styleCon);
cell = row.createCell(5);cell.setCellValue(pyNarcotics.getCriminalCondition());
cell.setCellStyle(styleCon);
cell = row.createCell(6);cell.setCellValue(pyNarcotics.getCensusRegion());
cell.setCellStyle(styleCon);
cell = row.createCell(7);cell.setCellValue(pyNarcotics.getLocalPolice());
cell.setCellStyle(styleCon);
cell = row.createCell(8);cell.setCellValue(pyNarcotics.getPresentAddress());
cell.setCellStyle(styleCon);
SimpleDateFormat dFormat=new SimpleDateFormat("yyyy-MM-dd");
cell = row.createCell(9);cell.setCellValue((pyNarcotics.getArrestDate()==null)?"":dFormat.format(pyNarcotics.getArrestDate()));
cell.setCellStyle(styleCon);
}
return wb;
} catch (Exception e) {
System.err.println(e.getMessage());
}
return wb;
}
}
我的controller层调用代码:
/**
* 导出人员数据带图片
*/
@RequiresPermissions("py:pyNarcotics:view")
@RequestMapping(value = "exportNarData")
public void exportNarData(PyNarcotics pyNarcotics, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
pyNarcotics.setStateNum(1);
//设置人员默认按照xx时间来排序
if(pyNarcotics.getOrderBy() == null){
pyNarcotics.setOrderBy("control_time ASC, update_date DESC");
}
pyNarcotics.setPage(null);
List<PyNarcotics> pyNarcoticsList= pyNarcoticsService.findList(pyNarcotics);
// 生成Excel
//excel标题
String[] title={"姓名","照片","身份证","手机号","微信号","xx","xx","xx","现住址","时间"};
//excel名称
String fileName = "人员数据.xls";
//sheet名
String sheetName = "人员信息";
HSSFWorkbook wb = ExportUtils.getHSSFWorkbook(sheetName, title, pyNarcoticsList,null);
//响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();os.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
//发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
我的前端页面(list)代码:
<!-- html里面的按钮显示 -->
<a href="#" class="btn btn-default" id="btnExportNew" title="${text('导出')}"><i class="glyphicon glyphicon-export"></i> ${text('导出')}</a>
//js层的代码(导入按钮根据ID绑定点击事件)
//"#btnExport"导出按钮的id #searchForm from表单的id
$('#btnExportNew').click(function(){
js.ajaxSubmitForm($('#searchForm'), {
url:'${ctx}/py/pyNarcotics/exportNarData',
downloadFile:true
});
});
其中查阅了很多博客,POI功能挺强大的,基本能实现对office的各种操作,字体样式你想要多么花里胡哨网上都有相应的案例和文档,感谢活在2019,热心网民是真的贴心窝,主要参考的博客我没有记录,但是有一个记了下来:https://blog.csdn.net/qq_40100817/article/details/82799036
学无止境!加油,我不认输!