java poi导出图片到excel示例代码
作者:954L 时间:2023-10-30 00:13:17
本文实例为大家分享了java使用poi导出图片到Excel的具体代码,供大家参考,具体内容如下
代码实现
Controller
/**
* 导出志愿者/人才数据
* @param talent_type
* @return
*/
@RequestMapping("/exportData")
public void exportData(Integer talent_type, HttpServletResponse response) {
String fileId = UUID.randomUUID().toString().replace("-", "");
Map<String, Object> param = new HashMap<>() ;
param.put("talent_type", talent_type) ;
try {
List<Map<String, Object>> volunteerMapList = volunteerService.getExportData(param) ;
String rootPath = SysConfigManager.getInstance().getText("/config/sys/rootPath");
String filePath = rootPath + "/" + fileId + ".xlsx" ;
volunteerService.exportData(volunteerMapList, filePath) ;
// 下载
FileInputStream inputStream = null;
try{
//设置发送到客户端的响应内容类型
response.reset();
response.setContentLength((int) new File(filePath).length());
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("文件名.xlsx", "UTF-8")+ "\"");
//读取本地图片输入流
inputStream = new FileInputStream(filePath);
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
while ((len = inputStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
} finally{
if(inputStream != null){
inputStream.close();
}
}
logger.debug("导出志愿者/人才数据成功!");
} catch (Exception e) {
e.printStackTrace();
logger.error("导出志愿者/人才数据异常!");
}
}
Service
public void exportData(List<Map<String, Object>> volunteerMapList, String filePath) throws Exception {
String[] alias = {"头像", "名称", "个人/团体", "志愿者/人才", "性别", "生日", "手机号",
"身份证", "省份", "市", "区/县", "详细地址", "邮箱", "政治面貌", "学历", "民族",
"职业", "团队人数", "艺术特长", "介绍"};
String[] keys = {"photo", "name", "type", "talent_type", "sex", "birth_day", "mobile",
"idcard", "province", "city", "county", "address", "email", "political",
"education", "nation", "profession", "member_count", "art_spetiality", "content"};
File file = new File(filePath);
if (!file.exists()) file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
int sheetSize = volunteerMapList.size() + 50;
double sheetNo = Math.ceil(volunteerMapList.size() / sheetSize);
String photoImgPath = SysConfigManager.getInstance().getText("/config/sys/rootPath") ;
for (int index = 0; index <= sheetNo; index++) {
XSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(index, "人才、志愿者" + index);
XSSFRow row = sheet.createRow(0);
sheet.setColumnWidth(0, 2048);
XSSFCell cell;
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
// 居中
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 加粗
cellStyle.setFont(font);
//创建标题
for (int i = 0; i < alias.length; i++) {
cell = row.createCell(i);
cell.setCellValue(alias[i]);
cell.setCellStyle(cellStyle);
}
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, volunteerMapList.size());
cellStyle = workbook.createCellStyle();
// 居中
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 写入各条记录,每条记录对应excel表中的一行
for (int i = startNo; i < endNo; i++) {
int rowNum = i + 1 - startNo ;
row = sheet.createRow(rowNum);
Map<String, Object> map = (Map<String, Object>) volunteerMapList.get(i);
for (int j = 0; j < keys.length; j++) {
cell = row.createCell(j);
String key = keys[j] ;
if (key.equals("photo")){
sheet.addMergedRegion(new CellRangeAddress(i + 1,i + 1,i + 1,i + 1)) ;
// 头像
File photoFile = new File(photoImgPath + map.get(key)) ;
if (photoFile.exists()){
BufferedImage bufferedImage = ImageIO.read(photoFile) ;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", byteArrayOut);
byte[] data = byteArrayOut.toByteArray();
XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor(480, 30, 700, 250, (short)0, i + 1, (short) 1, i + 2);
drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG));
sheet.setColumnWidth((short)500, (short)500);
row.setHeight((short)500);
} else {
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue("");
}
} else {
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
Object value = map.get(key);
cell.setCellValue(value == null ? "" : value.toString());
cell.setCellStyle(cellStyle);
}
}
}
// 设置列宽
for (int i = 1; i < alias.length; i++)
sheet.autoSizeColumn(i);
// 处理中文不能自动调整列宽的问题
this.setSizeColumn(sheet, alias.length);
}
fileOutput.flush();
workbook.write(fileOutput);
fileOutput.close();
}
// 自适应宽度(中文支持)
private void setSizeColumn(XSSFSheet sheet, int size) {
for (int columnNum = 0; columnNum < size; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
XSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
XSSFCell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) columnWidth = length;
}
}
}
columnWidth = columnWidth * 256 ;
sheet.setColumnWidth(columnNum, columnWidth >= 65280 ? 6000 : columnWidth);
}
}
以上所述是小编给大家介绍java poi导出图片到excel示例代码解整合,希望对大家有所帮助。
来源:https://blog.csdn.net/wkh___/article/details/87431066
标签:java,poi,excel
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Kotlin 协程异步热数据流的设计与使用讲解
2022-09-21 18:30:32
![](https://img.aspxhome.com/file/2023/4/138644_0s.jpg)
Grow heap (frag case) 堆内存过大的深入解析
2023-04-28 15:30:27
C#中Socket与Unity相结合示例代码
2022-09-15 23:24:15
通过特性(attribute)为枚举添加更多信息示例
2023-10-10 09:22:06
springboot2.0和springcloud Finchley版项目搭建(包含eureka,gateWay,Freign,Hystrix)
2021-09-14 22:57:38
![](https://img.aspxhome.com/file/2023/0/125640_0s.png)
Unity实现仿3D轮转图效果
2023-11-24 12:26:56
![](https://img.aspxhome.com/file/2023/7/83247_0s.gif)
c# ArrayList的使用方法小总结
2023-04-13 17:16:22
java.exe和javaw.exe的区别及使用方法
2022-08-27 10:03:39
![](https://img.aspxhome.com/file/2023/0/113250_0s.png)
Android Intent传递大量数据出现问题解决
2021-11-07 10:16:13
SpringMVC实现数据绑定及表单标签
2022-03-24 18:06:47
![](https://img.aspxhome.com/file/2023/8/68568_0s.png)
AndroidStudio接入Unity工程并实现相互跳转的示例代码
2023-08-06 23:34:51
![](https://img.aspxhome.com/file/2023/6/84736_0s.gif)
Java实现LeetCode(1.两数之和)
2021-06-03 02:11:19
Java实现解出世界最难九宫格问题
2022-06-14 19:47:10
Java实现合并多个PDF的示例代码
2023-04-29 13:25:32
如何将默认的maven仓库改为阿里的maven仓库
2022-09-30 14:16:31
![](https://img.aspxhome.com/file/2023/6/61526_0s.png)
使用IntelliJ IDEA搭建SSM框架的图文教程
2022-06-14 00:56:19
![](https://img.aspxhome.com/file/2023/7/94747_0s.png)
Java调用接口如何获取json数据解析后保存到数据库
2023-11-16 15:01:36
![](https://img.aspxhome.com/file/2023/8/59058_0s.png)
Java实现生成JSON字符串的三种方式分享
2022-05-20 15:21:31
C#编程实现统计文件夹内文件和隐藏文件的方法示例
2022-09-29 16:09:38
![](https://img.aspxhome.com/file/2023/3/74823_0s.jpg)
Java中双大括号初始化的理解与使用
2023-08-30 08:44:55