java Excel文件生成后转MultipartFile 完成文件上传。

由于需求。。

使用了ByteArrayOutputStream和ByteArrayInputStream类.
将XSSFWorkbook 写入ByteArrayOutputStream.然后用ByteArrayOutputStream来转换为字节流.然后再将字节流转换为ByteArrayInputStream …至此,我们就在内存中将excel转换成了输入流…
话不多说,上代码:

   //wb   为 XSSFWorkbook wb = new XSSFWorkbook();//创建一个Workbook
   //由于生成Excel代码太多... 
   ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] b = os.toByteArray();
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        String  strBase64 = ioToBase64(in);
        MultipartFile file = base64ToMultipart(strBase64);
        
        然后通过MultipartFile完成文件上传。..
// io转base64 
public static String ioToBase64(InputStream in) throws IOException {
        String strBase64 = null;
        try{
             //in.available()//返回文件的字节长度
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            // 将文件中的内容读入到数组中
            strBase64 = new BASE64Encoder().encode(bytes);   //将字节流数组转换为字符串
            in.close();
        }catch (IOException e) {
                e.printStackTrace();
            }
            return strBase64;
        }


    public static MultipartFile base64ToMultipart(String base64) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, base64);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
public class BASE64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        // TODO - implementation depends on your requirements
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }
}

参考博客:
https://blog.csdn.net/u011109420/article/details/51330677
https://blog.csdn.net/qq_37861937/article/details/78218547
https://blog.csdn.net/izb2008/article/details/79623234

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
首先,需要将OpenCV处理后的图片保存为Excel可以识别的格式,比如JPEG或PNG。 Java中可以使用ImageIO类读取图片并换格式,示例代码如下: ```java // 读取OpenCV处理后的图片 Mat mat = Imgcodecs.imread("path/to/image.jpg"); // 换为BufferedImage BufferedImage bufferedImage = new BufferedImage(mat.width(), mat.height(), BufferedImage.TYPE_3BYTE_BGR); mat.get(0, 0, ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData()); // 保存为PNG格式 ImageIO.write(bufferedImage, "png", new File("path/to/image.png")); ``` 接下来,可以使用Apache POI库创建Excel文件,并将换后的图片插入到Excel文件中,示例代码如下: ```java // 创建Excel工作簿 Workbook workbook = new XSSFWorkbook(); // 创建Excel工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 读取换后的图片 File imageFile = new File("path/to/image.png"); // 将图片插入到Excel文件中 InputStream inputStream = new FileInputStream(imageFile); byte[] bytes = IOUtils.toByteArray(inputStream); int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); inputStream.close(); CreationHelper helper = workbook.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(0); anchor.setRow1(0); Picture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(); // 保存Excel文件 FileOutputStream fileOutputStream = new FileOutputStream("path/to/excel.xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); workbook.close(); ``` 最后,可以使用Spring框架提供的MultipartFile接口,将生成Excel文件换成MultipartFile对象用于上传到服务器,示例代码如下: ```java // 读取生成Excel文件 File excelFile = new File("path/to/excel.xlsx"); // 创建MultipartFile对象 MultipartFile multipartFile = new MockMultipartFile(excelFile.getName(), new FileInputStream(excelFile)); ``` 通过以上步骤,就可以将OpenCV处理后的图片格式换为Excel文件,并且将其换为MultipartFile对象用于上传。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值