我有一项任务,我需要创建.xlsx并将其转换为base64,此文件将作为电子邮件webservice中的附件发送。将.xlsx转换为base64的代码如下:
import java.io.*;
import org.apache.commons.codec.binary.Base64;
public class Test {
public static void main(String [] args) {
String fileName = "C:/Users/kk.txt";
try {
byte[] buffer = new byte[1000];
FileInputStream inputStream =
new FileInputStream(fileName);
int total = 0;
int nRead = 0;
String reference=null;
while((nRead = inputStream.read(buffer)) != -1) {
String name=(new String(buffer));
byte[] encodedBytes = Base64.encodeBase64(name.getBytes());
System.out.println(new String(encodedBytes));
}
inputStream.close();
System.out.println("Read " + total + " bytes");
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
但是当我使用BPEL将其作为邮件发送时,当我打开文件时,它会显示一般输入/输出错误。但是当我将其作为文本发送时,它可以正常工作。我不应该将此代码用于excel或我错在哪里。对于java来说这是全新的。
答案 0 :(得分:1)
好的 - 我的猜测是你没有改变你为附件创建的电子邮件的mimetype等功能(默认情况下是text / html)。
看看here - 这是一个单词doc而不是 - 但概述了我认为你应该做的事情(假设我找到了正确的BPEL)
对于您的文件类型“.xlsx”,this table显示相应的mime类型就像
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
答案 1 :(得分:1)
package com.denemeler;
import java.io.*;
import java.util.Base64;
public class test {
public static void main(String[] args) throws IOException {
String filePath = "D:\\test.xls";
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fis.read(bytes);
String base64 = new sun.misc.BASE64Encoder().encode(bytes);
String destinationPath = "D:\\Destination\\donusmusHali.xls";
//decode Base64 String to image
FileOutputStream fos = new FileOutputStream(destinationPath);
bytes = new sun.misc.BASE64Decoder().decodeBuffer(base64);
fos.write(bytes);
fis.close();
fos.close();
}
}
此代码适用于编码和解码excel文件。
答案 2 :(得分:0)
通常,我们在outputStream中使用filename.xls编写我们的excel工作簿。 但是,如果需要通过网络以base64格式发送它,则可以选择ByteArrayOutputStream:
Workbook workbook = new HSSFWorkbook();
ByteArrayOutputStream b = new ByteArrayOutputStream();
try {
workbook.write(b);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
byte[] bytes = bos.toByteArray(
);
Base64.encodeBase64String(bytes);
此解决方案对我有用,因为首先使用Apache POI创建了excel,然后将其应用到上面的代码中,然后将其转换为base64,然后通过网络对其进行解码,然后按预期在excel应用程序中打开了编码文件。 :)
您可以在https://nupur28ag.blogspot.com/2020/01/get-base64-from-excel-created-using.html
上关注它