Editing a Excel template with POI in Netbeans - java

I have a Excel template wich I want to open, modify and save it like a normal book of excel when I click in a button in a Jframe.
This is the code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inp;
try {
inp = new FileInputStream("plantilla.xlt");
XSSFWorkbook wb = new XSSFWorkbook(inp);
XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(1);
XSSFRow row = sheet.getRow(3);
XSSFCell cell1 = row.getCell(1);
XSSFCell cell2 = row.getCell(2);
cell1.setCellValue(0);
cell2.setCellValue(10000);
//FileOutputStream fileOut = new FileOutputStream("plantilla.xlt");
//wb.write(fileOut);
//fileOut.close();
} catch (IOException ioe) {
Logger.getLogger(DonnéesFE.class.getName()).log(Level.SEVERE, null,ioe);
}
}
This is new for me so I have a couple questions:
I have to put the whole file path to get the FileInputStream? Is the extension .xlt correct? Right now it doesn't find the file. I have tried with the normal .xlsx extension and it finds it (I don't think it found the good file either) but I get this error on the definition of the workbook that I don't understand:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException.`
When I finish editing the excel template how I save it as a new excel book? Everybody uses a new file to save the output but I think that won't work here.

Related

How do i create a multiple sheets in same workbook on base of dropdown selection using Apache POI?

I have to select the option one after another from dropdown say (AAA,BBB... GGG) and after selection whatever the data populate have to be written on excel. Here method clickOnPerfomanceDetails() contains the code to write it down onto Excel. My following code is writing successfully onto excel with different sheets but manually i comment other options. In all 7 times i am executing the script to get data into 7 different worksheet.
public void clickOnPerformanceDetails() throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet("AAA");
//XSSFSheet sheet = wb.createSheet("BBB");
//XSSFSheet sheet = wb.createSheet("CCC");
// XSSFSheet sheet = wb.createSheet("DDD");
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
performance_PlusTWO.hoverTest();
performance_PlusTWO.clickOnHieararchyDropDown();
performance_PlusTWO.selectOptionNais();
//AAA
performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails();
//BBB
//performance_PlusTWO.selectBBBOption();
//performanceP_TWO.clickOnPerformanceDetails();
//CCC
performance_PlusTWO.selectAAAOption();
performance_TWO.clickOnPerformanceDets();
}
Creating 'AAA' worksheet and running Test for performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails(); Then manually i comment 'AAA' option, uncomment 'BBB' option and again execute the script. How do on a single click i execute the data for all the options.
Any help will be appreciated.
Try the below approach.
public void WriteToExcelSheet(String SheetName) throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet(SheetName);
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
Select dropdown = new Select(driver.findElement(By.id("id")));
//Get all options
List<WebElement> dropdown_items = dropdown.getOptions();
//print the number of dropdown items
System.out.println(dropdown_items.size());
// Loop through all items one by one
for (int itemIndex = 0; j < dd.size(); j++) {
String option = dropdown_items.get(itemIndex).getText();
//print the sheet name
System.out.println(option);
// write the logic to select the option <=== don't forget to implement this
// logic to call function with sheet name
performance_TWO.WriteToExcelSheet(option);
}
}

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

Apache POI not "Saving" excel file

I am writing a small utility that creates a pivot table in an excel sheet using POI and I want to read the data from the pivot table back to the program which will save it as a PDF file using Itext. I am running into a problem where the program cannot read the data from the pivot table after it is created. The program only can "see" the information in the pivot table after I manually open the created file and hit the save button in excel. Does anyone know a way to read the data from the pivot table from the XSSFPivotTable object or otherwise force a way for the file to "save" so it can be accessed by the program again?
Here is a snippet of code so you can see what I'm talking about. I'm a student so any advice on best practices would be greatly appreciated as well.
public void returnPivotData() throws IOException {
FileInputStream fs = new FileInputStream(this.xlsxFile);
XSSFWorkbook book = new XSSFWorkbook(fs);
XSSFSheet dataSheet = book.getSheet("Sheet1");
AreaReference dataRef = new AreaReference("A1:E15",
SpreadsheetVersion.EXCEL2007);
XSSFPivotTable table = dataSheet.createPivotTable(dataRef,
new CellReference("A16"));
table.addRowLabel(0);
table.addColumnLabel(DataConsolidateFunction.SUM, 3);
// Save the data back to the file
FileOutputStream fsOut = new FileOutputStream(
"D:\\workspace\\test.xlsx");
book.write(fsOut);
fsOut.close();
book.close();
fs.close();
// This does not allow access
FileInputStream fsIn = new FileInputStream("D:\\workspace\\test.xlsx");
XSSFWorkbook bookNew = new XSSFWorkbook(fsIn);
XSSFSheet sheet = bookNew.getSheet("Sheet1");
for (int i = 0; i < 20; i++) {
XSSFRow rowNew = sheet.getRow(i);
XSSFCell cellNew = rowNew.getCell(0,
MissingCellPolicy.CREATE_NULL_AS_BLANK);
System.out.println(cellNew.toString());
}
fsIn.close();
bookNew.close();
}

Error while creating read only .xlsx file using Apache POI

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);

Creating new sheet using Apache POI removes all the existing sheets

I trying to add new sheet to an existing excel file using Apache poi library as in the below code.
FileOutputStream fileOut = new FileOutputStream(new File(BASE_PATH+outputFile));
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Splitted Rules");
Set<String> tags = outputRules.keySet();
int i = 0;
for (String tag : tags) {
List<String> rules = outputRules.get(tag);
for (String rule : rules) {
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(tag);
row.createCell(1).setCellValue(rule);
}
}
wb.write(fileOut);
fileOut.close();
wb.close();`
The problem is that all the sheets in the file is deleted and only the new sheets exist.
What is this problem ?
The comments already hint at the solution.
The code above creates a new workbook and overwrites any existing file.
If you want to append a sheet to an existing workbook use the WorkbookFactory.create method (or the XSSFWorkbook constructors with the appropriate argument) to create the workbook based on the existing excel file.

Categories