I need to create a file .csv with apache-poi but this file is empty. For this example I want to create only header about this file so I do:
public byte[]...(File save_file) {
Workbook workbook = null;
Sheet sheet = null;
FileOutputStream outputStream=null;
try {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet();
createHeader(0,sheet);
outputStream = new FileOutputStream(save_file);
workbook.write(outputStream);
} catch (Exception exception) {
log.error("ERROR", exception);
} finally {
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.writeTo(outputStream);
log.info("SOTTO BYTE "+byteArrayOutputStream.toByteArray().length);
return byteArrayOutputStream.toByteArray();
}
and after the method "create_header":
private static void createHeader(int rowPosition,Sheet sheet) {
Row row = sheet.createRow(rowPosition);
Cell cell = row.createCell(1);
cell.setCellValue("DATE");
cell = row.createCell(2);
cell.setCellValue("EMAIL");
}
The problem is the file is empty. In the first method I need to return the byte[] that represents the csv file. Anyone can help me?
Related
I'm trying to create a .xlsx file using XSSFWorkBook in Java.
Using below code I'm trying
try
{
File tempFile = new File(validateFileUrl);
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
if(!rowList.isEmpty()) // rowList contains comma(,) separated string values
{
workbook = new XSSFWorkbook();
sheet = workbook.createSheet();
int rownum=0;
for(String rowStr : rowList)
{
XSSFRow row = sheet.createRow(rownum++);
String[] cellArr = rowStr.split(",");
int cellCount=0;
for(String cellStr : cellArr)
{
XSSFCell crrCell = row.createCell(cellCount++);
crrCell.setCellValue(cellStr);
}
}
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
workbook.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
file got created successfully, but the problem is that created file is opening in Read only mode, How can I create this in writeable mode?
I have tried the below option also
tempFile.setWritable(true);
but its not working, please help on this. Thanks
Excel will not allow editing a file that some other application is still writing. Instead it is waiting for exclusive access.
You need to ensure in Java the file buffer gets closed when you are finished writing the file. This happens either when the JVM terminates or when your code explicitly closes the FileOutputStream. Note that explicitly calling close can be tricky in case exceptions get thrown. Here is a safe way that makes use of the AutoClose feature of FileOutputStream:
try {
File tempFile = new File(validateFileUrl);
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
if(!rowList.isEmpty()) { // rowList contains comma(,) separated string values
workbook = new XSSFWorkbook();
sheet = workbook.createSheet();
int rownum=0;
for(String rowStr : rowList) {
XSSFRow row = sheet.createRow(rownum++);
String[] cellArr = rowStr.split(",");
int cellCount=0;
for(String cellStr : cellArr) {
XSSFCell crrCell = row.createCell(cellCount++);
crrCell.setCellValue(cellStr);
}
}
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
workbook.write(fos);
}
workbook.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
Note that vice versa, Excel is exclusively holding access to the file. So if you want to write it again from your application, ensure Excel has closed the document.
Fix is to close the FileOutputStream object
fos.close();
Sample Code:
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;
public class Excel {
public static void main(String[] args) {
String validateFileUrl = "so-excel.xlsx";
List<String> rowList = Arrays.asList("1", "2");
try
{
File tempFile = new File(validateFileUrl);
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
if(!rowList.isEmpty()) // rowList contains comma(,) separated string values
{
workbook = new XSSFWorkbook();
sheet = workbook.createSheet();
int rownum=0;
for(String rowStr : rowList)
{
XSSFRow row = sheet.createRow(rownum++);
String[] cellArr = rowStr.split(",");
int cellCount=0;
for(String cellStr : cellArr)
{
XSSFCell crrCell = row.createCell(cellCount++);
crrCell.setCellValue(cellStr);
}
}
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
System.out.println("Workbook created!!");
workbook.close();
fos.close(); //To close the FileOutputStream object
System.out.println("File Output Stream closed!!");
}
Thread.currentThread().sleep(600000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}
How to save symbols like 🔥🔥 to xlsx file using Java 8 and Apache POI library?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("\uD83D\uDD25\uD83D\uDD25");
try {
FileOutputStream outputStream = new FileOutputStream("text.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
As a result, I get a file with symbols "????" Instead of "🔥🔥".
I would like to add password protection to a xlsx file created with poi 3.14.
The documentation claims, that this is possible:
http://poi.apache.org/encryption.html
Using the example I tried it like this:
public static void main(String[] args)
{
try(Workbook wb = new XSSFWorkbook())
{
//<...>
try(ByteArrayOutputStream baos = new ByteArrayOutputStream())
{
wb.write(baos);
byte[] res = baos.toByteArray();
try(ByteArrayInputStream bais = new ByteArrayInputStream(res))
{
try(POIFSFileSystem fileSystem = new POIFSFileSystem(bais);) // Exception happens here
{
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("pass");
OutputStream encryptedDS = enc.getDataStream(fileSystem);
OPCPackage opc = OPCPackage.open(new File("example.xlsx"), PackageAccess.READ_WRITE);
opc.save(encryptedDS);
opc.close();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Unfortunately, the code in the example is not compatible to XLSX files and as a result I receive the following exception:
The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
Can anybody help please? I am unable to find the correct alternative for XLSX...
Thank you all for you help. Here is my working result:
public static void main(String[] args)
{
try(Workbook wb = new XSSFWorkbook())
{
Sheet sheet = wb.createSheet();
Row r = sheet.createRow(0);
Cell cell = r.createCell(0);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Test");
try(POIFSFileSystem fileSystem = new POIFSFileSystem();)
{
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("pass");
OutputStream encryptedDS = enc.getDataStream(fileSystem);
wb.write(encryptedDS);
FileOutputStream fos = new FileOutputStream("C:/example.xlsx");
fileSystem.writeFilesystem(fos);
fos.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You've mis-read the documentation on encrypting in OOXML file. You're therefore incorrectly trying to load your file using the wrong code, when you just need to save it
Without any error handling, your code basically wants to be
// Prepare
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");
// Create the normal workbook
Workbook wb = new XSSFWorkbook();
Sheet s = wb.createSheet();
// TODO Populate
// Encrypt
OutputStream os = enc.getDataStream(fs);
wb.save(os);
opc.close();
// Save
FileOutputStream fos = new FileOutputStream("protected.xlsx");
fs.writeFilesystem(fos);
fos.close();
I am trying to create one read only Excel-sheet using Apache POI 3.10.
private void lockAll(Sheet s, String password) throws Exception{
XSSFSheet sheet = ((XSSFSheet)s);
sheet.protectSheet(password);
sheet.enableLocking();
sheet.lockSelectLockedCells();
sheet.lockSelectUnlockedCells();
}
Now I am calling this method after creating my excel sheet using following.
private String generateExcel(List<Model> DataList) {
Workbook wwbook = null;
File ff = null;
try {
String filePath = // getting this path using ServletContext.
wwbook = new XSSFWorkbook();
Sheet wsheet = wwbook.createSheet("MyReport");
ApachePoiExcelFormat xlsxExcelFormat = new ApachePoiExcelFormat();
CellStyle sheetHeading = xlsxExcelFormat.SheetHeading(wwbook);
//My personal org.apache.poi.ss.usermodel.CellStyle here.
short col = 0, row = 0;
XSSFRow hrow = (XSSFRow) (XSSFRow) wsheet.createRow(row);
XSSFCell cell = hrow.createCell(col);
//My code here to iterate List and add data to cell.
FileOutputStream fileOut = new FileOutputStream(filePath.toString());
wwbook.write(fileOut);
lockAll(wsheet, "password"); //******calling the method to lock my sheet.
fileOut.close();
System.out.println("Excel Created");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return filePath;
}
Now while I am running this code to download the excel file. Then I am getting error on the webpage but not on my eclipse console.
Next I was trying to run the same code after commenting the following line in lockAll method. And then the excel downloading happens as required, but every cells in the sheet are editable.
sheet.protectSheet(password);