why is not possible to 'properly' hide an Excel row using Apache POI (3.16)? It is just possible to call (XSSFRow) row.setZeroHeight(), which is also what the Busy developer's guide recommends. However, this is not the same as hiding the row the way Excel does it. You can 'Hide' and 'Unhide' rows with the respective context menu options.
I thought setting the row style should work, but it doesn't. In the resulting Excel file, the row can still be seen.
package de.mwe;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.Test;
public class MWE {
#Test
public void testHidingRows() {
final XSSFWorkbook wb = new XSSFWorkbook();
String sname = "HideRowsTestSheet", cname = "TestName", cvalue = "TestVal";
XSSFSheet sheet = wb.createSheet( sname );
XSSFRow row = sheet.createRow( 0 );
XSSFCell cell = row.createCell( (short) 0 );
cell.setCellValue( cvalue );
XSSFCellStyle hiddenRowStyle = wb.createCellStyle();
hiddenRowStyle.setHidden( true );
row.setRowStyle( hiddenRowStyle );
Assert.assertTrue( row.getRowStyle().getHidden() );
try (FileOutputStream fileOut = new FileOutputStream( new File( "target/PoiTestDrive.xlsx" ) )) {
wb.write( fileOut );
} catch ( IOException ex ) {
ex.printStackTrace();
}
// does not work, resulting Excel file shows first row.
}
}
The Busy developer's guide is correct for hiding/unhiding rows. But there is a little error since it must be row.setZeroHeight(true); for hiding a row.
The Row.setZeroHeight(boolean) does exactly what Excel does while hiding a row. It works for HSSF as well as for XSSF. For XSSF it simply sets hidden property to the rows XML, see XSSFRow.java.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
public class CreateExcelHiddenRow {
public static void main(String[] args) throws Exception {
//Workbook wb = new HSSFWorkbook();
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
for (int r = 0; r < 3; r++) {
Row row = sheet.createRow(r);
Cell cell = row.createCell(0);
cell.setCellValue("Row " + (r+1));
}
Row row = sheet.getRow(1);
row.setZeroHeight(true);
//FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xls");
FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xlsx");
wb.write(out);
out.close();
wb.close();
}
}
You create a new row style. Instead, fetch the rows' existing Style and add your rule:
currentRow.getRowStyle().setHidden(true);
You kinda can refer to this post
Edit: You even create a new CellStyle as #RC mentioned.
Related
Im having difficulty with using Apache POI API. Im trying to import an excel them only select certain rows and cells to extract from the import. Im currently able to import, but i cant extract certain cell. Here is code:
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.io.IOException;
public class ExcelReader {
public static final String path = "C:/Users/xxxx/Documents/import testing.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
// Create a workbook with data from excel file
Workbook workbook = WorkbookFactory.create(new File(path));
// Save sheets from workbook
Sheet sheet = workbook.getSheetAt(0);
// Make sure the data is saved in string format using a data formatter
DataFormatter dataFormatter = new DataFormatter();
// Iterate through cells and columns, printing their content
System.out.println("\n\nThe content of the excel file: " + path + "\n");
String cellContent;
for (Row row: sheet) {
for(Cell cell: row) {
cellContent = dataFormatter.formatCellValue(cell);
if(cellContent == null || cellContent.trim().isEmpty()){
// Give the empty cells the content "empty", to make it easy to filter out later on
cellContent = "empty";
}
System.out.print(cellContent + "\t");
}
CellReference cellReference = new CellReference("A11");
XSSFRow rowT = sheet.getRow(cellReference.getRow());
if (rowT != null) {
XSSFCell cell = rowT.getCell(cellReference.getCol());
}
System.out.println();
}
// Close the connection to the workbook
workbook.close();
}
}
Changing Workbook to XSSFWorkbook and Sheet to XSSFSheet seems to fix the compilation issue.
XSSFWorkbook workbook = new XSSFWorkbook(new File(path));
and
XSSFSheet sheet = workbook.getSheetAt(0);
try with this for get "A11" cell
XSSFCell cell = sheet.getRow(10).getCell(0); // 10 = id of the 11th row, 0 = id of the 1st (A) column
or
XSSFCell cell = sheet.getRow(10).getCell(CellReference.convertColStringToIndex("A"));
create cell reference for B12
CellReference cr = new CellReference("B12");
row = mySheet.getRow(cr.getRow());
cell = row.getCell(cr.getCol());
I am trying to create an Excel sheet that contains an Excel table using Java with the Apache POI library but I couldn't get a result file that is readable by Microsoft Excel 2016 (Office 365). This is my code:
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
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.io.IOException;
class Scratch {
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Table Sheet");
XSSFRow row0 = sheet.createRow(0);
row0.createCell(0).setCellValue("#");
row0.createCell(1).setCellValue("Name");
XSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("Foo");
XSSFRow row2 = sheet.createRow(2);
row2.createCell(0).setCellValue("2");
row2.createCell(1).setCellValue("Bar");
AreaReference area = workbook.getCreationHelper().createAreaReference(
new CellReference(row0.getCell(0)),
new CellReference(row2.getCell(1))
);
sheet.createTable(area);
try(FileOutputStream file = new FileOutputStream(new File("workbook.xlsx"))) {
workbook.write(file);
}
}
}
The code runs fine but when I open the output file in Excel I get a message that the file has unreadable content.
I have tried running the official sample and the result is the same. The official sample can be found here: https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java
I need to know the minimum code required to get a readable table.
I am using version 4.0.0 of Apache POI with Oracle JavaSE JDK 1.8.0_172 on Windows 10.
Not sure what happens with the "official sample" codes always. They seems not even be tested.
The CreateTable uses XSSFTable table = sheet.createTable(reference); which creates a table having 3 columns as given from the area reference. But all of those have id 1, so we need repairing. And of course the columns should not be created again then.
So repaired sample code would be:
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
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.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFTableStyleInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Demonstrates how to create a simple table using Apache POI.
*/
public class CreateTable {
public static void main(String[] args) throws IOException {
try (Workbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
// Set which area the table should be placed in
AreaReference reference = wb.getCreationHelper().createAreaReference(
new CellReference(0, 0), new CellReference(2, 2));
// Create
XSSFTable table = sheet.createTable(reference); //creates a table having 3 columns as of area reference
// but all of those have id 1, so we need repairing
table.getCTTable().getTableColumns().getTableColumnArray(1).setId(2);
table.getCTTable().getTableColumns().getTableColumnArray(2).setId(3);
table.setName("Test");
table.setDisplayName("Test_Table");
// For now, create the initial style in a low-level way
table.getCTTable().addNewTableStyleInfo();
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
// Style the table
XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
style.setFirstColumn(false);
style.setLastColumn(false);
style.setShowRowStripes(true);
style.setShowColumnStripes(true);
// Set the values for the table
XSSFRow row;
XSSFCell cell;
for (int i = 0; i < 3; i++) {
// Create row
row = sheet.createRow(i);
for (int j = 0; j < 3; j++) {
// Create cell
cell = row.createCell(j);
if (i == 0) {
cell.setCellValue("Column" + (j + 1));
} else {
cell.setCellValue((i + 1.0) * (j + 1.0));
}
}
}
// Save
try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
wb.write(fileOut);
}
}
}
}
Btw.: My code from How to insert a table in ms excel using apache java poi works as well using apache poi 4.0.0. The sheet.createTable() is deprecated. So do using XSSFTable table = sheet.createTable(null); instead. Because the area as well as all other things is set using low level classes. Not even more code than the new example though.
I am trying the this testfile with the Apache POI API (current version 3-10-FINAL). The following test code
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelTest {
public static void main(String[] args) throws Exception {
String filename = "testfile.xlsx";
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(filename));
XSSFSheet sheet = wb.getSheetAt(0);
System.out.println(sheet.getFirstRowNum());
}
}
results in the first row number to be -1 (and existing rows come back as null). The test file was created by Excel 2010 (I have no control over that part) and can be read with Excel without warnings or problems. If I open and save the file with my version of Excel (2013) it can be read perfectly as expected.
Any hints into why I can't read the original file or how I can is highly appreciated.
The testfile.xlsx is created with "SpreadsheetGear 7.1.1.120". Open the XLSX file with a software which can deal with ZIP archives and look into /xl/workbook.xml to see that. In the worksheets/sheet?.xml files is to notice that all row elements are without row numbers. If I put a row number in the first row-tag like <row r="1"> then apache POI can read this row.
If it comes to the question, who is to blame for this, then the answer is definitely both Apache Poi and SpreadsheetGear ;-). Apache POI because the attribute r in the row element is optional. But SpreadsheetGear also because there is no reason not to use the r attribute if Excel itself does it ever.
If you cannot get the testfile.xlsx in a format which can Apache POI read directly, then you must work with the underlying objects. The following works with your testfile.xlsx:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import java.util.List;
class Testfile {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("testfile.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
System.out.println(sheet.getFirstRowNum());
CTWorksheet ctWorksheet = ((XSSFSheet)sheet).getCTWorksheet();
CTSheetData ctSheetData = ctWorksheet.getSheetData();
List<CTRow> ctRowList = ctSheetData.getRowList();
Row row = null;
Cell[] cell = new Cell[2];
for (CTRow ctRow : ctRowList) {
row = new MyRow(ctRow, (XSSFSheet)sheet);
cell[0] = row.getCell(0);
cell[1] = row.getCell(1);
if (cell[0] != null && cell[1] != null && cell[0].toString() != "" && cell[1].toString() != "")
System.out.println(cell[0].toString()+"\t"+cell[1].toString());
}
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
class MyRow extends XSSFRow {
MyRow(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow row, XSSFSheet sheet) {
super(row, sheet);
}
}
I have used:
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow
Which are part of the Apache POI Binary Distribution poi-bin-3.10.1-20140818 and there are within poi-ooxml-schemas-3.10.1-20140818.jar
For a documentation see http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/
And I have extend XSSFRow, because we can't use the XSSFRow constructor directly since it has protected access.
I'm trying to get updated cell values after use setForceFormulaRecal method. But I'm getting still old values. Which is not actual result. If I opened Original file by clicking It will asking update Links dialogue box. If I click "ok" button then Its updating all cell formula result. So I want to update excel sheet links before its open by using poi. Please help in this situation.
//Before Setting values
HSSFCell cel2=row1.getCell(2);
HSSFCell cel4=row1.getCell(5);
cel2.setCellValue(690);
cel4.setCellValue(690);
wb.setForceFormulaRecalculation(true);
wb.write(stream);
//After Evaluatting the work book formulas I'm trying as follow
HSSFWorkbook wb = HSSFReadWrite.readFile("D://workspace//ExcelProject//other.xls");
HSSFSheet sheet=wb.getSheetAt(14);
HSSFRow row11=sheet.getRow(10);
System.out.println("** cell val: "+row11.getCell(3).getNumericCellValue());
I'm Also tried with Formula Evaluator But its showing errors As follow
Could not resolve external workbook name '\Users\asus\Downloads\??? & ???? ?????_091230.xls'. Workbook environment has not been set up.
at org.apache.poi.ss.formula.OperationEvaluationContext.createExternSheetRefEvaluator(OperationEvaluationContext.java:87)
at org.apache.poi.ss.formula.OperationEvaluationContext.getArea3DEval(OperationEvaluationContext.java:273)
at org.apache.poi.ss.formula.WorkbookEvaluator.getEvalForPtg(WorkbookEvaluator.java:660)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:527)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:230)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:351)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateAllFormulaCells(HSSFFormulaEvaluator.java:324)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateAll(HSSFFormulaEvaluator.java:343)
at HSSFReadWrite.readSheetData(HSSFReadWrite.java:85)
at HSSFReadWrite.main(HSSFReadWrite.java:346)
Caused by: org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment$WorkbookNotFoundException: Could not resolve external workbook name '\Users\asus\Downloads\??? & ???? ?????_091230.xls'. Workbook environment has not been set up.
at org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment.getWorkbookEvaluator(CollaboratingWorkbooksEnvironment.java:161)
at org.apache.poi.ss.formula.WorkbookEvaluator.getOtherWorkbookEvaluator(WorkbookEvaluator.java:181)
at org.apache.poi.ss.formula.OperationEvaluationContext.createExternSheetRefEvaluator(OperationEvaluationContext.java:85)
... 11 more
OK, trying an answer:
First of all: Support for links to external workbooks is not included into the current stable version 3.10. So with this version it is not possible to evaluate such links directly. That's why evaluateAll() will fail for workbooks with links to external workbooks.
With Version 3.11 it will be possible to do so. But also only even if all the workbooks are opened and Evaluators for all the workbooks are present. See: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/FormulaEvaluator.html#setupReferencedWorkbooks%28java.util.Map%29
What we can do with the stable version 3.10, is to evaluate all the cells which contains formulas which have not links to external workbooks.
Example:
The workbook "workbook.xlsx" contains a formula with a link to an external workbook in A2:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
class ExternalReferenceTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
if (row == null) row = sheet.createRow(0);
Cell cell = row.getCell(0);
if (cell == null) cell = row.createCell(0);
cell.setCellValue(123.45);
cell = row.getCell(1);
if (cell == null) cell = row.createCell(1);
cell.setCellValue(678.90);
cell = row.getCell(2);
if (cell == null) cell = row.createCell(2);
cell.setCellFormula("A1+B1");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
//evaluator.evaluateAll(); //will not work because external workbook for formula in A2 is not accessable
System.out.println(sheet.getRow(1).getCell(0)); //[1]Sheet1!$A$1
//but we surely can evaluate single cells:
cell = wb.getSheetAt(0).getRow(0).getCell(2);
System.out.println(evaluator.evaluate(cell).getNumberValue()); //802.35
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
I have a program (below) that takes txt files and puts them into an excel spreadsheet. My goal is to extract the data from a text file but only text after the colon.
Example txt file(No space between "name:" and "phone:" lines in the txt):
Name: John doe
phone: (xxx) xxx-xxxx
I want my program to only save john doe in the excel sheet and title the column "Name":
I want my program to only save (xxx) xxx-xxxx in the excel sheet and title the column "phone"
I want to be able to add multiple entrys to the spreadsheet.
Example(in excel sheet generated):This is what i want it to look like!
....A..............B
1 name | Phone
2 john doe (123) 123-1234
3 jack dee (123) 123-1231
So i looked at the string split to get only data after the ":" but cant find much documentation on it. Also getting the info to line up correctly in the excel. Any help is much appreciated.
Thanks,
James
package EREW;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadWriteXL
{
public static void main(String[] args) throws InvalidFormatException, IOException{
ArrayList arr=new ArrayList();
File f=new File("F:\\temp\\TEXT\\email.txt");
Scanner in=new Scanner(f);
System.out.println("Read Data From The Txt file ");
while(in.hasNext())
{
arr.add(in.nextLine());
}
System.out.println("Data From ArrayList");
System.out.println(arr);
System.out.println("Write data to an Excel Sheet");
FileOutputStream fos=new FileOutputStream("F:/temp/1.xls");
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet spreadSheet = workBook.createSheet("email");
HSSFRow row;
HSSFCell cell;
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(arr.get(i));
cell.setCellValue(arr.get(i).toString());
}
System.out.println("Done");
workBook.write(fos);
arr.clear();
System.out.println("ReadIng From Excel Sheet");
FileInputStream fis = null;
fis = new FileInputStream("F:/temp/1.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row1 = (HSSFRow) rows.next();
Iterator cells = row1.cellIterator();
while (cells.hasNext()) {
HSSFCell cell1 = (HSSFCell) cells.next();
arr.add(cell1);
}
}
System.out.println(arr);
}}
If your file email.txt Always has the format you said:
Name: John
phone: (xxx) xxx-xxxx
I'm not familiarized with the row and cell creation, so I will give you some pseudo code to you understand what you have to do on your code:
On this part of your code:
//create a count for rows here
inr rowNumber = 0;
//Here you are reading your list with all data readed
for(int i=0;i<arr.size()-1;i+=2){ //the -1 is for the array to stop on the
//last but one row
row = spreadSheet.createRow((short) rowNumber); //external count
//pseudocode from here
cell1 = row.createCell(0);
cell2 = row.createCell(1);
cell1.setCellValue( arr.get(i).substring(arr.get(i).indexOf(":")+1) );
// ^ this is for name
cell2.setCellValue( arr.get(i+1).substring(arr.get(i+1).indexOf(":")+1) );
// ^ this is for phone
rowNumber++; //increment your rowNumber
}