The below code works fine on my local machine. But it does not work on the server - maybe because of permissions.
Can I make this work without actually creating a file on the server?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(Constants.SHEET_NAME);
for (Integer serialNo : reportReq.getSerialNos()) {
TraitsExceptionReport report = traitsExceptionReport.get(serialNo - 1);
Row row = sheet.createRow(rownum++);
createList(report, row);
}
File file = new File(Constants.TMP_FILE_NAME);
String absolutePath = file.getAbsolutePath();
FileOutputStream out = new FileOutputStream(file);
workbook.write(out);
FileInputStream fis = new FileInputStream(absolutePath );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
out.close();
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
throw new IOException("Exception while creating Traits Exception Report");
}
fis.close();
Files.deleteIfExists(Paths.get(absolutePath));
return(bos.toByteArray());
What is the standard way followed when developers will have to write a file on the unix servers.
POI 5.0.0 added a DeferredSXSSFWorkbook - works a bit like SXSSFWorkbook but doesn't need temp files - it uses a row generating function for each sheet that is executed lazily when you write out the workbook to an output stream.
I just added a simplistic sample to https://github.com/apache/poi/blob/trunk/src/examples/src/org/apache/poi/examples/xssf/streaming/DeferredGeneration.java
There are some tests and you might get the gist of how it works from
https://github.com/apache/poi/blob/trunk/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java
Related
I have a requirement to store the uploaded spreadsheet to the disk. I am using the below code to do the same and receiving the file is corrupted error from the excel.
byte[] bytes = null;
File uploadedFile = new File("D://xlsxTest//BNG Issue.xlsx");
File file = new File("D://xlsxTest//sample1.xlsx");
FileOutputStream outStream = null;
InputStream inputStream = null;
try{
if(!file.exists()){
file.createNewFile();
}
outStream = new FileOutputStream(file);
if (uploadedFile != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
inputStream = new FileInputStream(uploadedFile);;
int c = 0;
while (c != -1) {
c = inputStream.read();
byteArrayOutputStream.write((char) c);
}
bytes = byteArrayOutputStream.toByteArray();
}
outStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
I tried using a file of 83KB size and the resultant file is 82.5KB.
Any help would be appreciated.
Thanks.
Try using Apace POI, Convert .xls or .xlsx file to byte array using OPCPackage and XSSFWorkbook with below code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.open(new File(fullFileName));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
wb.write(baos);
byte[] fileContent = baos.toByteArray();
Apache POI takes care to extract all information of the excel file while converting to byte array.
I have created a jar for sending mail using java. I have to attach an excel file with mail. Am using HSSF for creating worksheet. But I need to encrypt the attachment with password. I succeeded. But when I open the attachment directly from mail through Outlook it's not asking password. and when I copy to any folder and then if I try to open , it works properly. Can anyone, please help?
public static void main(final String... args) throws Exception {
String fname = "D:\\Mail\\Sample.xls";
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
POIFSFileSystem poiFileSystem = null;
FileOutputStream fileOut = null;
try {
fileInput = new FileInputStream(fname);
bufferInput = new BufferedInputStream(fileInput);
poiFileSystem = new POIFSFileSystem(bufferInput);
Biff8EncryptionKey.setCurrentUserPassword("secret");
HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("THIS WORKS!");
fileOut = new FileOutputStream(fname);
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
File file = new File("D:\\Mail\\Sample.xls");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
}
byte[] bytes = bos.toByteArray();
// Code for sending mail
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
try {
bufferInput.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
try {
fileOut.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Method HSSFWorkbook.writeProtectWorkbook(...) is only meant to protect the workbook from being written to / modified.
If you try to open it in read+write mode (default in Windows folders), it will ask you for the password.
But if you open it in read-only mode, which is what Outlook does with attachments, it will let you view the contents since you can't write over them and thus you don't need the write password.
That's the reason you can view (but not edit) it in Outlook but not when you open it from a folder.
I don't know if the latest version of Apache POI supports full password protection for an HSSFWorkBook (a quick Google search says it doesn't, but who knows).
If it doesn't, you can work around this problem by making a password-protected ZIP file with the excel in it, and attaching the ZIP file instead.
I want to make an app that will download all the paper mentioned in the image by taking the domain as input. i have been able to download a single file from some other website but was unable to download a paper form acm digital library.
what i need to do is download the entire data set.
here is the code that i used to download a single file.
String fileName = "1.txt";
URL link = new URL("http://shayconcepts.com");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
How can I modify it to download entire data set
I'm creating a xlsx using poi and saving it on fileSystem. I need to download the file on a servlet call and due to memory constraints I did not create a xssf workbook object and used the following code instead :
byte[] buf = new byte[1024];
ServletOutputStream sOut = response.getOutputStream();
FileInputStream input = null;
try {
long length = fileToRead.length();
input = new FileInputStream(fileToRead);
while ((input != null) && ((length = input.read(buf)) != -1)) {
sOut.write(buf, 0, (int) length);
}
Where fileToRead is the file present at the file system.
How can I integrate this with How to create a zip file in Java
You could use
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
....
ze = new ZipEntry("xlsData");
zos.putEntry (ze);
// loop
zos.write(buf, 0, (int) length);
// finally
zos.close();
From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
One can utilize the autoclosable interface that was introduced in java 7.
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
Read from file or string to bytearray.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}