@RequestMapping(value = "/downData",method=RequestMethod.POST) public void…
- User
@RequestMapping(value = "/downData",method=RequestMethod.POST) public void downData(HttpServletRequest request, HttpServletResponse response) { List list = new ArrayList(); HSSFWorkbook book = null; OutputStream ouputStream = null;
String tid=request.getParameter("tid"); try { list = cs.fnidYdzrBaseDatas(tid); String title = "异地转入记录表"; book = cs.createYdzrPageSheet(title, list); if(!CollectionUtils.isEmpty(list) && book != null ){ //下载后文件名称 String displayName = "异地转入记录表"+"_" +MyDateUtils.getDateVal(new Date(), "yyyyMMddHH")+".xlsx"; //把服务器文件下载到浏览器客户端 String downFileName = new String(java.net.URLEncoder.encode(displayName,"UTF-8").getBytes(),"ISO8859-1"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + downFileName); ouputStream = response.getOutputStream(); book.write(ouputStream); ouputStream.flush(); } else { logger.info("下载异地转入列表信息为空,不能下载"); } } catch (Exception e) { logger.error("下载异地转入列表信息表格发生异常", e); }finally { if(book != null){ book = null; } if(ouputStream != null){ try { ouputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } - Assistant
This Java code defines a Spring MVC controller method that handles HTTP POST requests to the
/downDataendpoint. The purpose of this method is to generate and download an Excel file containing data about records of a specific type, based on a parameter provided in the request (tid). Below is an annotated explanation of the key parts of the code:import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; @RequestMapping(value = "/downData", method = RequestMethod.POST) public void downData(HttpServletRequest request, HttpServletResponse response) { List<YdzrExcleDetail> list = new ArrayList<>(); HSSFWorkbook book = null; OutputStream outputStream = null; String tid = request.getParameter("tid"); try { // Fetch data based on the provided 'tid' list = cs.fnidYdzrBaseDatas(tid); // Set the title for the Excel sheet String title = "异地转入记录表"; // Create the Excel workbook book = cs.createYdzrPageSheet(title, list); if (!CollectionUtils.isEmpty(list) && book != null) { // Set the download file name String displayName = "异地转入记录表_" + MyDateUtils.getDateVal(new Date(), "yyyyMMddHH") + ".xlsx"; // Encode the download file name for the response header String downFileName = new String(java.net.URLEncoder.encode(displayName, "UTF-8").getBytes(), "ISO8859-1"); // Set response headers response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + downFileName); // Write the workbook to the output stream outputStream = response.getOutputStream(); book.write(outputStream); outputStream.flush(); } else { logger.info("下载异地转入列表信息为空,不能下载"); } } catch (Exception e) { logger.error("下载异地转入列表信息表格发生异常", e); } finally { // Ensure resources are cleaned up properly if (book != null) { book = null; } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }Key Points to Note:
-
Annotation and Method Signature:
@RequestMapping(value = "/downData", method = RequestMethod.POST): Maps HTTP POST requests to thedownDatamethod.
-
Parameter Retrieval:
String tid = request.getParameter("tid");: Retrieves thetidparameter from the HTTP request.
-
Fetching Data:
list = cs.fnidYdzrBaseDatas(tid);: Calls a service method (assumed to be defined elsewhere) to fetch data based ontid.
-
Creating Excel Workbook:
book = cs.createYdzrPageSheet(title, list);: Another service method is called to create anHSSFWorkbookbased on the fetched list.
-
Handling Response:
- Content-type and headers are set to indicate an Excel file download.
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");- The file name for download is created and encoded properly to handle various browsers.
- The workbook is written to the response's output stream.
-
Error Handling:
- Uses a try-catch block to handle exceptions cleanly and logs any errors that occur during the process.
-
Resource Cleanup:
- Ensures that resources like the workbook and output stream are properly closed in the
finallyblock to prevent resource leaks.
- Ensures that resources like the workbook and output stream are properly closed in the
Improvements:
-
Use of Newer Apache POI Library Versions and Formats:
- Consider updating the use of
HSSFWorkbooktoXSSFWorkbookif working with.xlsxfiles to support the modern .xlsx format directly.
- Consider updating the use of
-
Error Handling & Logging:
- Make the exception logging more detailed if necessary, to capture and understand issues better.
-
Null and Size Checks:
- More consistent checks for null or empty values before proceeding with operations on the list or workbook.
-
Encapsulation and Reusability:
- Consider moving the file creation and download logic to a separate utility method or service class for better encapsulation and reusability.
-
- User
byte[] imageBytes = Base64.getDecoder().decode(base64Image); int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
InputStream inputStream = new ByteArrayInputStream(imageBytes); int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); // 设置图片位置 anchor.setCol1(7); anchor.setRow1(rowIdx - 1); anchor.setCol2(8); anchor.setRow2(rowIdx); drawing.createPicture(anchor, pictureIdx);上面是我往excle写入图片的一段代码 其中我得base64Image 是没有带data:image/png;base64,的头 现在是我导出的excle提示文件错误,数据可能丢失 请帮我分析原因
- Assistant
你的代码中有一些重复和潜在的问题,可能导致 Excel 文件错误。让我们逐步来看并解决这些问题。
问题分析
-
重复添加图片到工作簿
- 你的代码中调用了两次
workbook.addPicture,其中一次使用了imageBytes,一次使用了从InputStream中读取的字节数组。这会导致两个不同的图片索引,但是你在createPicture方法中只使用了第一个索引 (pictureIdx)。 - 这可能不会直接导致错误,但是它增加了工作簿中不必要的数据,可能引起其他问题。
- 你的代码中调用了两次
-
未关闭的资源
- 虽然你在示例代码中没有显示完整的资源管理,但确保
InputStream关闭是个好习惯。
- 虽然你在示例代码中没有显示完整的资源管理,但确保
修改建议
- 删除重复添加图片的代码,确保只添加一次图片。
- 确保资源在使用完后正确关闭。
- 确保
ClientAnchor位置设置和图片数据正确。
改进后的代码
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.IOUtils; public void insertImageToExcel(Workbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { byte[] imageBytes = Base64.getDecoder().decode(base64Image); // Add picture to the workbook (only once) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // Ensure that the InputStream is closed properly try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) { int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); } catch (IOException e) { throw new IOException("Error reading image bytes", e); } // Create a drawing canvas on the sheet Drawing drawing = sheet.createDrawingPatriarch(); // Create an anchor that the image can be attached to ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); // Specify the position in the Excel sheet anchor.setRow1(rowIdx - 1); anchor.setCol2(8); anchor.setRow2(rowIdx); // Create the picture in the Excel sheet using the anchor and the picture index drawing.createPicture(anchor, pictureIdx); }重点说明
-
Base64 解码:
- 确保
base64Image字符串是纯 Base64 编码的图片数据,不包含前缀data:image/png;base64,。
- 确保
-
一次添加图片:
int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);已足够,不需要重复执行这个操作。
-
资源管理:
- 使用
try-with-resources确保InputStream在操作完成后正确关闭。
- 使用
-
图片位置:
- 使用
ClientAnchor设置图片在工作表中的位置:anchor.setCol1,anchor.setRow1,anchor.setCol2,anchor.setRow2。
- 使用
排除其他问题
如果问题仍然存在,可以考虑以下步骤排查:
- 确认 Base64 编码图片数据的正确性。
- 确认 Excel 文件的其他部分没有问题,引入图片的部分是唯一修改的地方。
- 尝试在简单的、独立的 Excel 文件中执行这段代码验证基础功能。
通过这样的步骤,你应该能够解决 Excel 文件在打开时提示错误的问题。
-
- User
注销改成中文
- Assistant
好的,请参考以下修改后的代码,其中注释已经被翻译成中文:
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.IOUtils; public void insertImageToExcel(Workbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { // 将 Base64 图片数据转换为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片添加到工作簿(只添加一次) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // 确保 InputStream 正确关闭 try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) { int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); } catch (IOException e) { throw new IOException("读取图片字节时发生错误", e); } // 在工作表中创建绘图画布 Drawing drawing = sheet.createDrawingPatriarch(); // 创建图片锚点,可以将图片附加到此锚点 ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); // 指定图片在 Excel 表中的位置 anchor.setRow1(rowIdx - 1); anchor.setCol2(8); anchor.setRow2(rowIdx); // 使用锚点和图片索引在 Excel 表中创建图片 drawing.createPicture(anchor, pictureIdx); }重点说明
-
Base64 解码:
- 将
base64Image字符串解码为纯粹的 Base64 编码图片数据。
- 将
-
一次添加图片:
- 只需要执行
int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);一次即可,无需重复添加。
- 只需要执行
-
资源管理:
- 使用
try-with-resources确保InputStream在操作完成后正确关闭。
- 使用
-
图片位置:
- 使用
ClientAnchor设置图片在工作表中的位置:anchor.setCol1,anchor.setRow1,anchor.setCol2,anchor.setRow2。
- 使用
通过上述代码及注释,你可以清晰地了解每个步骤的作用,并确保图片正确地插入到 Excel 工作表中,同时避免之前的问题。
-
- User
能否给出完整的优化代码
- Assistant
当然可以,这里是完整的优化后的代码,包含了必要的导入和注释,以确保你可以直接使用:
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.IOUtils; public class ExcelImageInserter { /** * 将Base64编码的图片插入到Excel工作表的指定位置。 * * @param workbook Excel工作簿 * @param sheet 目标工作表 * @param base64Image Base64编码的图片字符串(不带前缀 data:image/png;base64,) * @param rowIdx 图片应插入的行索引 * @throws IOException 如果读取图片字节时发生错误 */ public static void insertImageToExcel(Workbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { // 将Base64图片数据转换为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片添加到工作簿(只添加一次) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // 确保InputStream正确关闭 try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) { // 此处其实不需要再次添加图片,因此可以删除这段代码 // int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); } catch (IOException e) { throw new IOException("读取图片字节时发生错误", e); } // 在工作表中创建绘图画布 Drawing drawing = sheet.createDrawingPatriarch(); // 创建图片锚点,可以将图片附加到此锚点 ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); // 指定图片在Excel表中的位置 anchor.setRow1(rowIdx - 1); anchor.setCol2(8); // 可以根据需要调整列范围 anchor.setRow2(rowIdx); // 可以根据需要调整行范围 // 使用锚点和图片索引在Excel表中创建图片 drawing.createPicture(anchor, pictureIdx); } }具体说明
- Base64 解码: 将
base64Image转换成字节数组。 - 添加图片: 将图片数据添加到工作簿中,并返回图片的索引。
- 创建绘图画布: 在目标工作表中创建一个绘图画布。
- 设置锚点: 使用
ClientAnchor来定义图片在工作表中的位置。 - 绘制图片: 使用绘图工具将图片绘制到工作表中。
改进点
- 删除多余代码: 删除了重复添加图片的方法调用,这确保只往工作簿中添加一次图片。
- 资源管理: 使用
try-with-resources语法以确保InputStream在操作完成后正确关闭,即使在使用时抛出异常。
通过这种方式,你可以更安全和有效地将Base64编码的图片插入到Excel工作表中,同时避免文件损坏等问题。
- Base64 解码: 将
- User
这个支持xls吗
- Assistant
原来的代码以及改进后的代码使用了Apache POI库中的
Workbook接口和相关API,这些API既可以用于处理.xlsx(Excel 2007及以上版本的文件格式),也可以用于处理.xls(Excel 97-2003版文件格式)。不过,为了确保特定版本的Excel文件兼容性,您需要明确使用
HSSFWorkbook(适用于.xls格式)或XSSFWorkbook(适用于.xlsx格式)。下面是如何修改代码,以确保支持.xls格式,即使用HSSFWorkbook类:import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.IOUtils; public class ExcelImageInserter { /** * 将Base64编码的图片插入到Excel工作表的指定位置。 * * @param workbook Excel工作簿 * @param sheet 目标工作表 * @param base64Image Base64编码的图片字符串(不带前缀 data:image/png;base64,) * @param rowIdx 图片应插入的行索引 * @throws IOException 如果读取图片字节时发生错误 */ public static void insertImageToExcel(HSSFWorkbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { // 将Base64图片数据转换为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片添加到工作簿(只添加一次) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // 确保InputStream正确关闭 try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) { // 此处其实不需要再次添加图片,因此可以删除这段代码 // int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); } catch (IOException e) { throw new IOException("读取图片字节时发生错误", e); } // 在工作表中创建绘图画布 Drawing drawing = sheet.createDrawingPatriarch(); // 创建图片锚点,可以将图片附加到此锚点 ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); // 指定图片在Excel表中的位置 anchor.setRow1(rowIdx - 1); anchor.setCol2(8); // 可以根据需要调整列范围 anchor.setRow2(rowIdx); // 可以根据需要调整行范围 // 使用锚点和图片索引在Excel表中创建图片 drawing.createPicture(anchor, pictureIdx); } }具体说明
- HSSFWorkbook: 使用
HSSFWorkbook类表示一个.xls格式的工作簿。 - 图片类型: 尽管
Workbook.PICTURE_TYPE_PNG是通用的图片类型常量,但确认其确实支持.xls格式。
用法示例
例如在创建工作簿、工作表,并调用插入图片的方法时:
public static void main(String[] args) throws IOException { // 创建一个 Excel 2003 工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // Base64 编码的图片字符串(去掉 "data:image/png;base64," 头) String base64Image = "iVBORw0KGgoAAAANSUhEUgAAA..."; // 这里应该是完整的 Base64 数据. // 行索引,假设在第1行插入图片 int rowIdx = 1; // 调用插入图片方法 ExcelImageInserter.insertImageToExcel(workbook, sheet, base64Image, rowIdx); // 保存到文件 try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) { workbook.write(fileOut); } }这样,你可以确保图片被正确地插入到一个
.xls格式的Excel文件中,并且在打开时不会提示文件错误或数据丢失。 - HSSFWorkbook: 使用
- User
xls对应的ContentType是什么
- Assistant
在处理文件下载时,设置正确的 MIME 类型非常重要,确保浏览器正确识别和处理文件。对于
.xls格式的 Excel 文件,其对应的 Content-Type 是application/vnd.ms-excel。下面是一个示例代码,展示如何在 Spring MVC 控制器中设置这个 Content-Type,以便客户端浏览器正确处理下载的
.xls文件。示例代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Base64; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.IOUtils; @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET) public void downloadExcel(HttpServletRequest request, HttpServletResponse response) { String base64Image = request.getParameter("base64Image"); // 获取Base64编码的图片 int rowIdx = Integer.parseInt(request.getParameter("rowIndex")); // 获取行索引 HSSFWorkbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); try { insertImageToExcel(workbook, sheet, base64Image, rowIdx); response.setContentType("application/vnd.ms-excel"); String filename = "workbook.xls"; response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); OutputStream out = response.getOutputStream(); workbook.write(out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } // 插入图片的辅助方法(同上文的示例方法) public static void insertImageToExcel(HSSFWorkbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { byte[] imageBytes = Base64.getDecoder().decode(base64Image); int pictureIdx = workbook.addPicture(imageBytes, HSSFWorkbook.PICTURE_TYPE_PNG); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); anchor.setRow1(rowIdx - 1); anchor.setCol2(8); anchor.setRow2(rowIdx); drawing.createPicture(anchor, pictureIdx); }关键点解释
-
设置 Content-Type:
response.setContentType("application/vnd.ms-excel");设置了响应的内容类型为.xls文件的 MIME 类型。
-
添加 Content-Disposition 头:
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");设置了文件下载时的文件名。
-
获取输出流并写入工作簿:
OutputStream out = response.getOutputStream();workbook.write(out);- 执行完写入操作后,正确地刷新和关闭输出流。
-
插入图片的辅助方法:
insertImageToExcel方法与前面的定义相同,用于将 Base64 编码的图片插入到指定位置的 Excel 工作表中。
测试
确保在客户端(如浏览器)正确测试文件下载功能,下载后的
.xls文件应当能正确打开,并且无提示文件损坏或数据丢失的信息。通过这种方式,您可以确保正确生成并提供
.xls格式的 Excel 文件下载,同时包含图片数据。 -
- User
现在我想做一点优化 我先把展示的图片大小改成200*200大小,要求excle的宽高也要适应,请你帮我优化一下代码 public HSSFWorkbook createYdzrPageSheet(String title, List list) throws IOException { // 创建工作簿 HSSFWorkbook workbook = new HSSFWorkbook();
// 创建表 Sheet sheet = workbook.createSheet(title); // 创建标题行 Row headerRow = sheet.createRow(0); Cell headerCell0 = headerRow.createCell(0); headerCell0.setCellValue("申请时间"); Cell headerCell1 = headerRow.createCell(1); headerCell1.setCellValue("申请驾校"); Cell headerCell2 = headerRow.createCell(2); headerCell2.setCellValue("准驾车型"); Cell headerCell3 = headerRow.createCell(3); headerCell3.setCellValue("身份证明名称"); Cell headerCell4 = headerRow.createCell(4); headerCell4.setCellValue("姓名"); Cell headerCell5 = headerRow.createCell(5); headerCell5.setCellValue("身份证明号码"); Cell headerCell6 = headerRow.createCell(6); headerCell6.setCellValue("原驾校名称"); Cell headerCell7 = headerRow.createCell(7); headerCell7.setCellValue("二维码"); int rowIdx = 1; for (YdzrExcleDetail detail : list) { Row row = sheet.createRow(rowIdx++); row.createCell(0).setCellValue(detail.getSqsj()); row.createCell(1).setCellValue(detail.getSqjx()); row.createCell(2).setCellValue(detail.getZjcx()); row.createCell(3).setCellValue(detail.getSfzmmc()); row.createCell(4).setCellValue(detail.getXm()); row.createCell(5).setCellValue(detail.getSfzmhm()); row.createCell(6).setCellValue(detail.getYjxmc()); // 假设图片数据是 base64 编码格式 String base64Image = detail.getBase64Image(); // 假设这个方法存在,替换为实际方法 if (StringUtils.isNotBlank(base64Image)) { insertImageToExcel(workbook,sheet,base64Image,rowIdx); } rowIdx++; } return workbook; }/** * 将Base64编码的图片插入到Excel工作表的指定位置。 * * @param workbook Excel工作簿 * @param sheet 目标工作表 * @param base64Image Base64编码的图片字符串(不带前缀 data:image/png;base64,) * @param rowIdx 图片应插入的行索引 * @throws IOException 如果读取图片字节时发生错误 */ public static void insertImageToExcel(HSSFWorkbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { // 将Base64图片数据转换为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image);
// 将图片添加到工作簿(只添加一次) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // 确保InputStream正确关闭 try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) { // 此处其实不需要再次添加图片,因此可以删除这段代码 // int pictureIndex = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG); } catch (IOException e) { throw new IOException("读取图片字节时发生错误", e); } // 在工作表中创建绘图画布 Drawing drawing = sheet.createDrawingPatriarch(); // 创建图片锚点,可以将图片附加到此锚点 ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setCol1(7); // 指定图片在Excel表中的位置 anchor.setRow1(rowIdx - 1); anchor.setCol2(8); // 可以根据需要调整列范围 anchor.setRow2(rowIdx); // 可以根据需要调整行范围 // 使用锚点和图片索引在Excel表中创建图片 drawing.createPicture(anchor, pictureIdx); } - Assistant
为了使插入的图片在Excel中显示为200x200像素,并调整相应的单元格大小以适应图片,我们需要:
- 调整插入图片时的锚点设置。
- 设置相应行和列的高度和宽度。
预处理
我们需要了解以下情况以适应图片大小:
- Excel列宽的单位是字符宽度(其中一个单位约等于1/256字符宽度)。
- Excel行高的单位是点(points)(其中一个点约等于1/72英寸)。
完整优化后的代码
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Cell; public class ExcelImageInserter { public HSSFWorkbook createYdzrPageSheet(String title, List<YdzrExcleDetail> list) throws IOException { // 创建工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); // 创建表 Sheet sheet = workbook.createSheet(title); // 创建标题行 Row headerRow = sheet.createRow(0); Cell headerCell0 = headerRow.createCell(0); headerCell0.setCellValue("申请时间"); Cell headerCell1 = headerRow.createCell(1); headerCell1.setCellValue("申请驾校"); Cell headerCell2 = headerRow.createCell(2); headerCell2.setCellValue("准驾车型"); Cell headerCell3 = headerRow.createCell(3); headerCell3.setCellValue("身份证明名称"); Cell headerCell4 = headerRow.createCell(4); headerCell4.setCellValue("姓名"); Cell headerCell5 = headerRow.createCell(5); headerCell5.setCellValue("身份证明号码"); Cell headerCell6 = headerRow.createCell(6); headerCell6.setCellValue("原驾校名称"); Cell headerCell7 = headerRow.createCell(7); headerCell7.setCellValue("二维码"); int rowIdx = 1; for (YdzrExcleDetail detail : list) { Row row = sheet.createRow(rowIdx++); row.createCell(0).setCellValue(detail.getSqsj()); row.createCell(1).setCellValue(detail.getSqjx()); row.createCell(2).setCellValue(detail.getZjcx()); row.createCell(3).setCellValue(detail.getSfzmmc()); row.createCell(4).setCellValue(detail.getXm()); row.createCell(5).setCellValue(detail.getSfzmhm()); row.createCell(6).setCellValue(detail.getYjxmc()); // 假设图片数据是 base64 编码格式 String base64Image = detail.getBase64Image(); // 假设这个方法存在,替换为实际方法 if (StringUtils.isNotBlank(base64Image)) { insertImageToExcel(workbook, sheet, base64Image, rowIdx); } rowIdx++; } return workbook; } /** * 将Base64编码的图片插入到Excel工作表的指定位置。 * * @param workbook Excel工作簿 * @param sheet 目标工作表 * @param base64Image Base64编码的图片字符串(不带前缀 data:image/png;base64,) * @param rowIdx 图片应插入的行索引 * @throws IOException 如果读取图片字节时发生错误 */ public static void insertImageToExcel(HSSFWorkbook workbook, Sheet sheet, String base64Image, int rowIdx) throws IOException { // 将Base64图片数据转换为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片添加到工作簿(只添加一次) int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG); // 在工作表中创建绘图画布 Drawing drawing = sheet.createDrawingPatriarch(); // 创建图片锚点,可以将图片附加到此锚点 ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); // 指定图片在Excel表中的位置 anchor.setCol1(7); anchor.setRow1(rowIdx - 1); anchor.setCol2(8); anchor.setRow2(rowIdx); // 使用锚点和图片索引在Excel表中创建图片 drawing.createPicture(anchor, pictureIdx); // 调整行高和列宽以适应图片大小 sheet.setColumnWidth(7, 200 * 256 / 7); // 约 28.57 字符宽,256 是一个字符宽度单位的标量 Row row = sheet.getRow(rowIdx - 1); if (row != null) { row.setHeightInPoints(200); // 200像素 => 200 点(1像素约等于1点) } } }关键点解释
-
行和列尺寸调整:
- 将列宽设置为适应图片的宽度(约28.57个字符宽),因为列宽单位是1/256字符宽度。
- 将行高设置为适应图片的高度(200点),因为行高单位是点(1点约等于1/72英寸)。
-
图片位置:
- 使用
ClientAnchor将图片锚定到指定的单元格。
- 使用
-
图片插入与整理:
- 添加图片到工作簿中,并创建绘图画布和对应的图片对象。
- 调整相关的行高和列宽以适应图片大小。
用法
这个优化后的代码可以在创建Excel并插入Base64编码的图片时,确保图片大小为200x200像素,并自动调整对应单元格的尺寸以适应图片的显示。