Why it outputs an error"Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (0) is out of range (no sheets)"
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileInputStream;
import java.io.IOException;
public class test {
public static void main(String[] args) throws IOException {
Workbook wb = new HSSFWorkbook();
FileInputStream fis = new FileInputStream("C:/Users/KP/IdeaProjects/JavaExcel/read.xls");
String result = wb.getSheetAt(1).getRow(1).getCell(1).getStringCellValue();
System.out.println(result);
fis.close();
}
}
You created a new Workbook and access the sheet at Index 1.
If you want to load your Inputstream to your workbook you need to create a new Workbook with the InputStream.
You should also use try with resources to close your stream and workbook.
try (InputStream in = new FileInputStream("C:/Users/KP/IdeaProjects/JavaExcel/read.xls");
Workbook wb = new HSSFWorkbook(in)) {
String result = wb.getSheetAt(1).getRow(1).getCell(1).getStringCellValue();
System.out.println(result);
}
Please notice that getSheetAt(1) returns the second sheet. If you want the first sheet you need to use getSheetAt(0). Same goes for getRow and getCell. So if you want the first cell in the first row in the first workbook use:
String result = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue();
declare/ Initialize the workbook after file input stream like below by passing fis object
FileInputStream fis = new FileInputStream("C:/Users/KP/IdeaProjects/JavaExcel/read.xls");
Workbook wb = new HSSFWorkbook(fis);
hope you have data in the second sheet of excel file as mentioned "wb.getSheetAt(1)", if not make it wb.getSheetAt(0)
Related
I simply want to put the result of a Java program into an Excel cell. Let's assume the result is 5, then my code in main() would look like this:
XSSFWorkbook wb = C:\Users\Username\Desktop\java-programs\results.xlsm;
XSSFSheet ExcelSheet = wb.getSheet("numbers");
XSSFRow row = ExcelSheet.getRow(0);
XSSFCell cell = row.getCell(0);
cell.setCellValue(5);
However, this code doesn't compile.
I read some examples on this topic but the code given simply refers to the Excel sheet as (e.g.) "sheet" and then goes on with sheet.getRow(some number). The examples don't explain how I tell Java which workbook to write to.
Your first line is incorrect.. try this:
String fileName = "C:/Users/Username/Desktop/java-programs/results.xlsm";
FileInputStream fileIn = new FileInputStream(fileName);
Workbook wb = WorkbookFactory.create(fileIn);
// update the workbook
wb.getSheet("numbers").getRow(0).getCell(0).setCellValue(5);
fileIn.close();
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.close();
I have a method that reads an excel sheet using Apache POI library. To make that method generic, I need to to write some code in a catch block. Here's the method:
private List<String[]> readFile(String filePath) throws IOException{
List<String[]> sheetValues = new ArrayList<String[]>();
//Two types of fileInputStreams for both the types of workbook i am about to use
//
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
FileInputStream fileInputStream2 = new FileInputStream(new File(filePath));
LineItemFileReader fileReader = new LineItemFileReaderImpl();
//If the file is in xls format i should use HSSFWorkbook
//If the file is in xlsx format i should use XSSFWorkbook
try {
//If the file is in xlsx format then the below line will throw the
//Exception and catch block code will be executed
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
} catch (OfficeXmlFileException exception){
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream2);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
} finally{
fileInputStream.close();
fileInputStream2.close();
}
return sheetValues;
}
So what's happening here is that I dont know what type of file I am being supplied. I am deciding that on the basis of the try/catch block given above. So is there any generic way of deciding which workbook to use? Since the above code has flow control logic written in a catch block, it's a bad practice.
Use WorkbookFactory.create(...) for opening the Workbook. It will create the appropriate subclass internally:
Workbook workbook = WorkbookFactory.create(new File(filePath));
// ...
workbook.close();
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();
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!)
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());
}