Read excel file byte array - java

byte[] test = getByteArry(excelfikepath)
I have one method where it returns the bytearray of the excel .xlsx file. To read this file i need to write these byte array using FileOutputStream on one server and from there i am calling another method which will read and process that excel from the server.
There is some limitation because of which i cant read excel file directly i have to put it onto another server and process.
Just wanted to know is there any way by which i can make use of this byte array and read excel file IN MEMORY instead of writing it on server.

This will help to get byte array out of an excel file.
public static byte[] getFileByteArr(String fileName) throws InvalidFormatException, IOException {
try (OPCPackage opcPackage = OPCPackage.open(new File(fileName))) {
try (XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(opcPackage)) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook.write(bos);
return bos.toByteArray();
}
}
}
}

Related

Why does my code ( ZipOutputStream ) saves empty file in ZIP?

I have a simple code that is supposed to make txt file zipped, though txt file has some content, it's empty in a zip folder ( it has 89 bytes ( like buffer ) but all are just spaces.
The interesting part is that if I write
byte[] buffer = Files.readAllBytes(path);
my code is working.
I am new to java and would appreciate your help a lot. Because I trully don't understand what I am doing wroing.
public class Test {
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("C:\\Users\\10\\Desktop\\ds.txt");
ZipInputStream zis = new ZipInputStream(fis);
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(Paths.get("C:\\Users\\10\\Desktop\\ds.zip")))) {
byte[] buffer = new byte[fis.available()];
zos.putNextEntry(new ZipEntry("ds.txt"));
zis.read(buffer);
zos.write(buffer);
zos.closeEntry();
}
Since the text file is not zipped yet, don't use a ZipInputStream to read it. Just use the FileInputStream, or even better the NIO.2 File API (you're using it already to create the ZipOutputStream but not to create the InputStream).
There is even a file system provider for the NIO.2 File API to read/ write to Zip files using the same API: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html (For Java 11+ the following module is required: https://docs.oracle.com/en/java/javase/11/docs/api/jdk.zipfs/module-summary.html)
Also make sure to use try-with-resources for the OutputStream as well, not just the InputStream, to properly close the stream in the finally block.

Convert string and byte[] to file in JAVA

I have an interface with this strings and bytes array
public interface EmailAttachment {
String getFileName();
String getFileVersion();
byte[] getContent();
String getType();
}
i want to put all of this in a file, in my class Service how could i called?:
#Override
public Boolean sendEmail(EmailAttachment attachment) {
File file = new File( "HERE,I want to bring everything");
uploadFile(file);
}
If i use attachment.getFileName(),attachment.getFileVersion(),attachment.getContent(),attachment.getType()
it brings me an error because the file needs a path
try this out create a File object with the file name and pass it on to FileOutputStream.
OutputStream accepts byte array to store it in file, once uploading done close the stream.
String FILENAME = "";
File file = new File(FILENAME);
OutputStream os = new FileOutputStream(file);
// here you can write bytes to file using FileOutputStream
os.write(bytes);
// Close the file
os.close();

how to get the inputStream from Workbook object in java

When I upload the file i am passing the inputstream to the workbook. Now I want to use this InputStream from workbook in another method like save where I save the file InputStream in to DB. Here is my code.
public void FileUpload(FileUploadEvent event) throws ParseException {
UploadedFile item = event.getUploadedFile();
Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(item.getInputStream());
}
Now I want to make Workbook object as instance variable and pass to another method like below.
public String save() throws SQLException, IOException{
fileId = dao.savefile(workbook,fileName);
}
In my savefile method
InputStream inptest= **workbook.getStream**
ps.setBinaryStream(2,fin,fin.available());
So inptest variable accepts InputStream which I wanted to get it from Workbook.
It sounds like what you are asking for is a way to use the InputStream for multiple purposes:
To create a Workbook object (which you're already doing)
To save the content of that InputStream somewhere else
Since reading from an InputStream is usually a one-time-only operation that cannot be repeated, then you can do the following:
Save the full content of the InputStream to a buffer.
Open two new InputStreams from the buffer.
Pass your InputStreams to your two methods.
Code might look like this:
public void FileUpload(FileUploadEvent event) throws ParseException {
UploadedFile item = event.getUploadedFile();
InputStream originalInputStream = item.getInputStream();
byte[] buffer = IOUtils.toByteArray(originalInputStream);
InputStream is1 = new ByteArrayInputStream(buffer);
InputStream is2 = new ByteArrayInputStream(buffer);
Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(is1);
}
InputStream inptest = is2;
ps.setBinaryStream(2,fin,fin.available());
Note: this uses Apache Commons IO library for IOUtils.
If you are trying to save the Workbook object to a file, there is a method write() which takes in an OutputStream. Saving to a file can then be accomplished by
FileOutputStream fos = new FileOutputStream("path/to/file/[filename]");
workbook.write(fos);
fos.close();

Xlsx file corupted when downloading

I created an xlsx file using XSSF from apache-poi and creating a route which returns this file using apache-camel.
The file is created ok, I made all the possible content settings that I found, download is working without any problems on my local machine (windows).
After deploying it to a Unix server (under Tomcat7) and accesing the http path from that server, the file is downloaded but it is corrupted, excel will not open it. I receive the following errors:
"Excel found unreadable content in 'Filename.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes." After I click yes follow up error shows:
"Excel cannot open the file 'Filename.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
I am using a processor called from camel to create the Workbook file, and create all the content settings in the processor, this should not be a problem, I logged them outside the processor and all is set. Also everything is working as it should, but only on local PC.
Note: I have the same version of Java/apache-camel/poi/tomcat and so on.. like the server.
Some code snippet:
XSSFWorkbook xlsx = writeToExcel(list);
ByteArrayOutputStream bos = getByteFormat(exchange, xlsx);
exchange.getIn().setHeader("Content-Disposition",
"attachment; filename=ProductExports.xlsx");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE,"application/vnd.openxml");
exchange.getIn().setHeader(Exchange.CONTENT_LENGTH,bos.toByteArray().length);
exchange.getIn().setHeader("Expires","0");
exchange.getIn().setBody(bos.toByteArray());
The getByteFormat() part:
private ByteArrayOutputStream getByteFormat(Exchange exchange,
XSSFWorkbook xlsx) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
xlsx.write(bos);
} finally {
bos.close();
}
return bos;
}
I searched around but didn't find any examples with camel-poi, where people encountered the same problems.
Note: I tried also with HSSF format, and with different CONTENT_TYPE settings, the result is the same.
I guess maybe the problem is caused cause I pass the byte array and somehow Unix systems are interpreting this in a different way, or maybe something with file transfer partitioning. The corrupted file has a bigger dimension then the one which is created normally, probably contains some extra lines, not sure if this matters.
Below the code working fine in Windows and Unix. Hope this will may help you.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OutputStream outStream = null;
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader
("Content-Disposition", "attachment; filename=Sample.xlsx");
outStream = response.getOutputStream();
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
wb.write(outStream);
outStream.close();
}
catch (Exception e){
throw new ServletException("Exception in Excel Sample Servlet", e);
}
finally{
if (outStream != null)
outStream.close();
}
}

How to save text file without overwriting?

I want to save in a text file without overwriting the current data. I mean the next data that will be save will go to the new/next line whenever I save and that is my problem, I don't know how to do that.
Could someone help me about this matter?
Here's the code in save() method :
public void save(String filename) throws IOException
{
FileOutputStream fOut = new FileOutputStream(filename);
ObjectOutputStream outSt = new ObjectOutputStream(fOut);
outSt.writeObject(this);
}
Read the docs
public FileOutputStream(File file, boolean append) throws FileNotFoundException
Creates a file output stream to write to the file represented by the
specified File object. If the second argument is true, then bytes will
be written to the end of the file rather than the beginning. A new
FileDescriptor object is created to represent this file connection.

Categories