Delete an excel sheet using Apache POI - java

I have to delete a sheet from the Excel file.
Here's my code snippet :
FileInputStream fileStream = new FileInputStream(destFile);
POIFSFileSystem fsPoi = new POIFSFileSystem(fileStream);
HSSFWorkbook workbook = new HSSFWorkbook(fsPoi);
int index = 0;
HSSFSheet sheet = workbook.getSheet("Setup");
if(sheet != null) {
index = workbook.getSheetIndex(sheet);
workbook.removeSheetAt(index);
}
return destFile;
After this I'm getting exactly the same workbook which I passed, without the removal of the sheet "Setup"
Help me resolve this. Any help would be appreciated

After editing your workbook, you need to write it again. Try this:-
FileOutputStream output = new FileOutputStream(destFile);
workbook.write(output);
output.close();
Edit:- After writing it back, you can return your destFile.

private void removeOtherSheets(String sheetName, XSSFWorkbook book) {
for(int i=book.getNumberOfSheets()-1;i>=0;i--){
XSSFSheet tmpSheet =book.getSheetAt(i);
if(!tmpSheet.getSheetName().equals(sheetName)){
book.removeSheetAt(i);
}
}
}

Delete a sheet using Apache POI
//Open file
FileInputStream inputStream = new FileInputStream(new File(filePath));
XSSFWorkbook workBook = new XSSFWorkbook(inputStream);
//Delete Sheet
workBook.removeSheetAt(resultWorkbook.getSheetIndex("SheetToBeDeleted"));
//Save the file
FileOutputStream outFile =new FileOutputStream(new File(filePath));
workBook.write(filePath);
outFile.close();

Related

How to close XSSF file with out.close()?

I am trying to save and close an existing workbook that I am already successfully opening but for some reason cannot either save and close:
//declarations etc here...
try {
InputStream ExcelFileToRead = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
//XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(file)));
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
int rows;
rows = sheet.getPhysicalNumberOfRows();
int cols = 1;
XSSFRichTextString path;
String stpath;
try {
if(!Desktop.isDesktopSupported()){
System.out.println("Error: Desktop is not supported");
}
Desktop desktop = Desktop.getDesktop();
if(filee.exists()) desktop.open(filee);
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
//code continues...
wb.write(out) opens the file successfully. I have read tons of posts/articles/docs all using that close() method to close out an XSSF Excel file but it does not work here.
How do I solve the problem?
You cannot overwrite the input document this way, as clearly documented in the Javadoc for POIXMLDocument#write(OutputStream o) which is inherited by XSSFWorkBook:
Note - if the Document was opened from a File rather than an InputStream, you must write out to a different file, overwriting via an OutputStream isn't possible

How I can read excel file and set value to null

I want to read a excel file and if there is any data then I want to set it to null then start writing to it. This is what I have for setting excel sheet data to null. I able to write successfully but before write I want to set the value null.
FileOutputStream out = null;
try{
FileInputStream file = new FileInputStream(new File("/test.xls"));
HSSFWorkbook oldFile = new HSSFWorkbook(file);
HSSFSheet sheet = oldFile.getSheetAt(0);
file.close();
oldFile.write(null);
outFile.close();
} catch(Exception e){
e.printStackTrace();
}
One easy solution is to delete and create a sheet:
File destFile = new File("/test.xls");
FileInputStream fileStream = new FileInputStream(destFile);
POIFSFileSystem fsPoi = new POIFSFileSystem(fileStream);
HSSFWorkbook workbook = new HSSFWorkbook(fsPoi);
int index = 0;
HSSFSheet sheet = workbook.getSheet("Setup");
if(sheet != null) {
index = workbook.getSheetIndex(sheet);
workbook.removeSheetAt(index);
}
workbook.createSheet("Setup");
FileOutputStream output = new FileOutputStream(destFile);
workbook.write(output);
output.close();

File Excel From Apache POI Cant Open by Ms Excel (corrupt)

I don't know why the file I write using POI cant be opened by Ms Excel 2013, but the file is still readable by POI. (cell value can be changed)
this is the error from file
here is the code
FileInputStream fis = null;
try {
fis = new FileInputStream(fileUri); //not error at fileUri
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String urii = fileUri.replace(".xls", "0.xls"); //not error
File fisx = new File(urii);
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String p = cell.getStringCellValue();
TextView a = (TextView) findViewById(R.id.txtUri);
cell.setCellValue(new String("popo"));
String x = cell.getStringCellValue();
TextView b = (TextView) findViewById(R.id.txtFile);
a.setText(p);
b.setText(x);
OutputStream fos = null;
fos = new FileOutputStream(fisx);
workbook.write(fos); //main problem
fos.flush();
fos.close();
Thanks for your help!!
There are two issues with your code. Firstly this:
FileInputStream fis = null;
try {
fis = new FileInputStream(fileUri);
As explained in the Apache POI Docs, don't use an InputStream if you have a File!
Secondly, this:
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
That will only work for .xls files, not for .xlsx ones. Instead, you need to use WorkbookFactory which identifies the type and gives you the right workbook for the format
So, change your code to be
File file = new File(fileUri);
Workbook workbook = WorkbookFactory.create(file);
The major problem that i see here is:
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
Instead you have to use:
Workbook workbook = null;
workbook = new XSSFWorkbook(fis);
TO be readable by MS EXCEL 2013.
Solved :
by using real android device instead of bluestack emulator,
I dont know why, but it works!!
Thanks everyone :D
You are calling getSheetAt(0) but you did not create any sheet before (workbook.createSheet(“name”)
The solution is to use the .xls extension and NOT .xlsx, as outlined in this answer

Java POI Create new Workbook with SS model?

I'm a little confused, I used to do this:
HSSFWorkbook wb = new HFFSWorkbook();
But with the new POI, I dont have to do that.
I can't do this:
Workbook wb = new Workbook();
I understand WorkbookFactory.create, but that is for opening a file.
How do I set up a new workbook with this ss model?
You can still use the SS model but need to decide on the file format at the time of creation.
For xls -> Workbook wb = new HSSFWorkbook();
For xlsx -> Workbook wb = new XSSFWorkbook();
In "New POI", you can write/read both XLS files and XLSX files. In any case, for XLS file-format you were using:
HSSFWorkbook wb = new HSSFWorkbook();
So for XLSX file-format, you have to use:
XSSFWorkbook wb = new XSSFWorkbook();
// you could also do below
// Workbook wb = new XSSFWorkbook();
Also it would be helpful for you if you refer below links for starting with XLS to XLSX migration.
1. http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html
2. http://poi.apache.org/spreadsheet/converting.html
Make sure you download and add the POI JAR file to your project’s class path before running the code. The Apache POI JAR file can be found here.
public void main(String[] args) throws IOException {
// Directory path where the xls file will be created
String destinationFilePath = "C:/Users/devesh_/Documents/HelloWorld.xls";
// Create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(destinationFilePath);
// Build the Excel File
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HSSFWorkbook workBook = new HSSFWorkbook();
// Create the spreadsheet
HSSFSheet spreadSheet = workBook.createSheet("Hello_World");
// Create the first row
HSSFRow row = spreadSheet.createRow((short) 0);
// Create the cells and write to the file
HSSFCell cell;
// Write Hello
cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("Hello"));
// Write World
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("World"));
workBook.write(outputStream);
outputStream.writeTo(fout);
outputStream.close();
fout.close();
}
When creating a file, you need to decide up front what format it'll be - you can't just wait until write-out time to do that. You code would be something like:
Workbook wb = null;
if (shouldBeXLS) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
// work on the file in a generic way
// save, with a suitable name
String filename = "test.xls";
if (!shouldBeXLS) { filename = filename + "x"; }
FileOutputStream fout = new FileOutputStream(filename);
wb.write(fout);
fout.close();
At the start, decide what format you want for this particular instance, and create that. Treat it as a general workbook, and write to it in the common way. At the end, remember what it is so you can give the file the right extension!
(When reading a file in, WorkbookFactory will let you load the appropriate instance for the file type. When creating a new file, you have to pick yourself as there's nothing there yet!)

Count number of worksheets in Excel File

How to count number of worksheets in a Microsoft Excel file using Java SE?
There's no standard class/library files in Java SE that interfaces with MS Excel. In Apache POI, you can use HSSFWorkbook.getNumberOfSheets() method which returns you the number of worksheet from a workbook.
To open an Excel file and get HSSFWorkbook, do this:
String fileName = "C://Excel.xls";
POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
USE THE FOLLOWING CODE TO GET number of worksheets
FileInputStream file = new FileInputStream(new File(FILE PATH));
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("number of sheet::"+ workbook.getNumberOfSheets());
Use getNumberOfSheets() in the WritableWorkbook class.
Take a look at these:
jxl.Workbook;
jxl.write.Label;
jxl.write.WritableSheet;
jxl.write.WritableWorkbook;
http://jexcelapi.sourceforge.net/resources/javadocs/2_6_10/docs/jxl/write/WritableWorkbook.html
public int getNumberOfSheets(File)throws Exception{
FileInputStream fileInputStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
int number_of_sheets = workbook.getNumberOfSheets();
return number_of_sheets
}
Above is a simple method to get the number of sheets in an xls workbook
You can use xlsx4j to count. This is my code:
public static void main(String[] args) throws InvalidFormatException, Docx4JException {
SpreadsheetMLPackage spPackage = SpreadsheetMLPackage.load(new File("D:/MyFile.xlsx"));
List<Sheet> sheetList = spPackage.getWorkbookPart().getJaxbElement().getSheets().getSheet();
System.out.println("Number of worksheet: "+ sheetList.size());
System.out.println("Sheet name: ");
for (Sheet sheet : sheetList) {
System.out.println(sheet.getName());
}

Categories