I have three or more excel files with different sheets among them and I need to create a new blank file with a copy (or clone) that sheets into the new file and place them in the order I need so I can fill out the respective forms with data.
How can I do this by using Jakarta POI (XSSFWorkbook)?
First up, I think you mean Apache POI - it hasn't been Apache Jakarta POI for quite a few years now...
In terms of copying sheets from one workbook to another, it can be done, but it will require some coding. First you'll want to identify the cell styles you use, and clone those across. Make sure you keep track of which source Cell Style goes to which destination Cell Style, as you don't want to keep re-creating or you'll hit the limit! CellStyle.cloneStyleFrom(CellStyle) is the method you'll want.
Then, for each source sheet, create a sheet in the target workbook. Loop over all the source rows, creating new target ones. Then loop over the cells, switch by cell type, grab the appropriate value and set it. Rinse and repeat!
FileOutputStream os = new FileOutputStream("differnetFileName")
readWorkbook.write(os);
guess we can make use of write operation to OS with diff file name will work .
This is my implementation of copying sheets from one workbook to another. I did everything as described by Gagravarr. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
Related
I am using the Apache POI library to export data to Excel. I have tried all the latest versions (3.17, 4.1.2, and 5.2.1).
I have a problem with Excel 97 (.xls) format in relation to cell styles. The cell style somehow is lost (or not displayed) after a certain number of columns.
Here is my sample code:
private void exportXls() {
try (
OutputStream os = new FileOutputStream("test.xls");
Workbook wb = new HSSFWorkbook();) {
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
CellStyle cs = wb.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.WHITE.index);
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
c.setCellStyle(cs);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
And the result as viewed by MS Excel 2019
Viewed by MS Excel
As you can see, the style/format is lost after cell 43rd.
But, when I open the same file by other applications like XLS Viewer Free (from Microsoft Store) or Google Sheets (online), the style/format still exists and is displayed well.
Viewed by XLS Viewer Free
Viewed by Google Sheets
Could anyone please tell me what is going on here?
Did I miss something in my code?
Is there any hidden setting in MS Excel that causes this problem?
Thank you.
Creating cell styles for each single cell is not a good idea using apache poi. Cell styles are stored on workbook level in Excel. The sheets and cells share the cell styles if possible.
And there are limits for maximum count of different cell styles in all Excel versions. The limit for the binary *.xls is less than the one for the OOXML *.xlsx.
The limit alone cannot be the only reason for the result you have. But it seems as if Excel is not very happy with the 50 exactly same cell styles in workbook. Those are memory waste as only one shared style would be necessary as all the 50 cells share the same style.
Solutions are:
Do creating the cell styles on workbook level outside cell creating loops and only set the styles to the cells in the loop.
Example:
private static void exportXlsCorrect() {
try (
OutputStream os = new FileOutputStream("testCorrect.xls");
Workbook wb = new HSSFWorkbook();) {
CellStyle cs = wb.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.WHITE.index);
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
c.setCellStyle(cs);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Sometimes it is not really possible to know all possible needed cell styles before creating the cells. Then CellUtil can be used. This has a method CellUtil.setCellStyleProperties which is able to set specific style properties to cells. Doing that new cell styles are created on workbook level only if needed. If already present, the present cell styles are used.
Example:
private static void exportXlsUsingCellUtil() {
try (
OutputStream os = new FileOutputStream("testUsingCellUtil.xls");
Workbook wb = new HSSFWorkbook();) {
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
java.util.Map<java.lang.String,java.lang.Object> properties = new java.util.HashMap<java.lang.String,java.lang.Object>();
properties.put(org.apache.poi.ss.util.CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.WHITE.index);
properties.put(org.apache.poi.ss.util.CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.LIGHT_BLUE.getIndex());
properties.put(org.apache.poi.ss.util.CellUtil.FILL_PATTERN, FillPatternType.SOLID_FOREGROUND);
org.apache.poi.ss.util.CellUtil.setCellStyleProperties(c, properties);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
I am reading an xlsx file using java (Apache POI).
I have created a Document class (having all excel column heading as variables)
i have to read each row in the excel and map to the Document class by creating a collection of Document class.
The problem I am facing is that I have to start reading from row 2 and from column 7 to column 35 and map the corresponding values to the document class.
Unable to to figure out exactly how the code should be ?
I have written the following lines of code.
List sheetData = new ArrayList();
InputStream excelFile = new BufferedInputStream(new FileInputStream("D:\\Excel file\\data.xlsx"));
Workbook workBook = new XSSFWorkbook(excelFile); // Creates Workbook
XSSFSheet sheet = (XSSFSheet) workBook.getSheet("Daily");
DataFormatter formatter = new DataFormatter();
for (int i = 7; i <= 35; i++) {
XSSFRow row = sheet.getRow(i);
Cell cell = row.getCell(i);
String val = formatter.formatCellValue(cell);
sheetData.add(val);
}
Assuming I've understood your question correctly, I believe you want to process every row which exists from row 2 onwards to the end of the file, and for each of those rows consider the cells in columns 7 through 35. I believe you also might need to process those values, but you haven't said how, so for this example I'll just stuff them in a list of strings and hope for the best...
This is based on the Apache POI documentation for iterating over rows and cells
File excelFile = new File("D:\\Excel file\\data.xlsx");
Workbook workBook = WorkbookFactory.create(excelFile);
Sheet sheet = workBook.getSheet("Daily");
DataFormatter formatter = new DataFormatter();
// Start from the 2nd row, processing all to the end
// Note - Rows and Columns in Apache POI are 0-based not 1-based
for (int rn=1; rn<=sheet.getLastRowNum(); rn++) {
Row row = sheet.getRow(rn);
if (row == null) {
// Whole row is empty. Handle as required here
continue;
}
List<String> values = new ArrayList<String>();
for (int cn=6; cn<35; cn++) {
Cell cell = row.getCell(cn);
String val = null;
if (cell != null) { val = formatter.formatCellValue(cell); }
if (val == null || val.isEmpty()) {
// Cell is empty. Handle as required here
}
// Save the value to list. Save to an object instead if required
values.append(val);
}
}
workBook.close();
Depending on your business requirements, put in logic for handling blank rows and cells. Then, do whatever you need to do with the values you find, again as per your business requirements!
You could iterate with an Iterator in the document, but there is also an function "getRow() and getCell()"
Workbook workbook = new XSSFWorkbook(excelFile);
// defines the standard pointer in document in the first Sheet
XSSFSheet data = this.workbook.getSheetAt(0);
// you could iterate the document with an iterator
Iterator<Cell> iterator = this.data.iterator();
// x/y pointer at the document
Row row = data.getRow(y);
Cell pointingCell = row.getCell(x);
String pointingString = pointingCell.getStringCellValue();
I have been trying my code to delete the empty rows inside my excel file! my code is:
private void shift(File f){
File F=f;
HSSFWorkbook wb = null;
HSSFSheet sheet=null;
try{
FileInputStream is=new FileInputStream(F);
wb= new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
for(int i = 0; i < sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
}
}
FileOutputStream fileOut = new FileOutputStream("C:/juni1.xls");
wb.write(fileOut);
fileOut.close();
//Here I want to write the new update file without empty rows!
}
catch(Exception e){
System.out.print("SERRO "+e);
}
}
The code has no effect at all. Can any body tell me what is the problem please help me i have been trying to do the thing since last 10 hours. thanks in advance!
There will be two cases when any row is blank.
First, the Row is in between the other rows, but never be initialized or created. In this case Sheet.getRow(i) will be null.
And Second, the Row was created, its cell may or may not get used but now all of its cells are blank. In this case Sheet.getRow(i) will not be null. (you can check it by using Sheet.getRow(i).getLastCellNum() it will always show you the count same as other rows.)
In general case the second condition occurs. Perhaps in your case, it should be the reason. For this you need to add additional condition to check whether all the cells are blank or not.
for(int i = 0; i < sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
continue;
}
for(int j =0; j<sheet.getRow(i).getLastCellNum();j++){
if(sheet.getRow(i).getCell(j).toString().trim().equals("")){
isRowEmpty=true;
}else {
isRowEmpty=false;
break;
}
}
if(isRowEmpty==true){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
}
}
Okay I'm not sure exactly why you're having a problem but I think it's due to the way in which you are accessing the Workbook. Let's assume that the file you send down file is the location of the XLS workbook that you want to work with. The first thing you need to check is if that workbook exists because the POI's handling of existing v nonexistent workbooks is differnt. That is accomplished as such:
HSSFWorkbook wb;
HSSFSheet sheet;
if(file.exists()) {//The workbook has been created already
wb = (HSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));//Line 1
sheet = wb.getSheetAt(0);
} else {//No workbook exists at the location the "file" specifies
wb = new HSSFWorkbook();
sheet = wb.createSheet();
}
A few notes: Line 1 throws 2 exceptions IOException from java.io.IOException and InvalidFormatException from org.apache.poi.openxml4j.exceptions.InvalidFormatException. So either throw the exceptions or surround with try-catch as you prefer.
Now if file always exists, than the if-else statement isn't really needed. However, to properly open the desired workbook I would use the WorkbookFactory.
As a final word, you can simplify your file saving by simply putting:
wb.write(new FileOutputStream("C:/juni1.xls");
Notice that you are also writing the saved file to a different location. Therefore your original workbook is untouched while the corrected one is in a different place.
I'm using apache poi to create an excel document. To create new sheet in workbook I write next code:
Workbook wb = new HSSFWorkbook();
Sheet sh = wb.createSheet();
this code create and add sheet to workbook. But I want to create sheet formerly and then add it to workbook. Smth like this:
Sheet sh = new HSSFSheet();
wb.addSheet(sh);
I need such thing, because I want to copy data from one sheet of one workbook to another sheet of another workbook(Workbook interface has method Sheet cloneSheet(int)). But Workbook interface doesn't have method like addSheet(Sheet sh).
Also HSSFWorkbook is final class so I can't extend it to implement add method
How can I do this?
You can't just take a Sheet object from one Workbook, and add it to a different Workbook.
What you'll need to do is to open the old workbook and the new workbooks at the same time, and create the sheet in the new workbook. Next, clone all the styles you used in the old sheet onto the new one (HSSFCellStyle has a method for cloning a style from one workbook to another). Finally, iterate over all the cells and copy them over.
You should use RangeCopier.
XSSFWorkbook workbookFrom = new XSSFWorkbook(new File("/path/to/workbookFrom.xlsx"));
XSSFSheet sheetFrom = workbookFrom.getSheetAt(0);
XSSFWorkbook workbookTo = new XSSFWorkbook(new File("/path/to/workbookTo.xlsx"));
XSSFSheet sheetTo = workbookTo.createSheet("sheet1");
workbookTo.setSheetOrder("sheet1", 0);
XSSFRangeCopier xssfRangeCopier = new XSSFRangeCopier(sheetFrom, sheetTo);
int lastRow = sheetFrom.getLastRowNum();
int lastCol = 0;
for (int i = 0; i < lastRow; i++) {
Row row = sheetFrom.getRow(i);
if (row != null) {
if (row.getLastCellNum() > lastCol) {
lastCol = row.getLastCellNum();
}
sheetTo.setDefaultRowHeight(sheetFrom.getDefaultRowHeight());
}
}
for (int j = 0; j < lastCol; j++) {
sheetTo.setColumnWidth(j, sheetFrom.getColumnWidth(j));
}
CellRangeAddress cellAddresses = new CellRangeAddress(0, lastRow, 0, lastCol);
xssfRangeCopier.copyRange(cellAddresses, cellAddresses, true, true);
workbookTo.write(new FileOutputStream(new File("/path/to/worksheetTo.xlsx")));
POI version < v4.0
Okay I tried to do what Gagravarr said above. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
POI version >= v4.0
As of version 4.0, Cell.CELL_TYPE_BLANK and Row.CREATE_NULL_AS_BLANK don't exist (they deprecated). Use CellType.* and Row.MissingCellPolicy.* instead.
I am currently using Apache POI to create empty excel files (that I will later read and edit). The problem is that whenever I try to get the cell, I always get a null value. I have tried initializing the first few columns and rows (the cells are no longer null) but with this approach, I cannot insert new rows and columns. How can I be able to initialize all cells of a sheet without having to set the number of rows and columns? Thanks
EDIT: Hi this is my code in creating excel files. I could not use the iterator to initialize all my cells since there are no rows and columns for the spreadsheet.
FileOutputStream fileOut = new FileOutputStream(loc + formID +".xls");
HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
for (Row row : sheet) {
for (Cell cell : row) {
CellStyle style = workbook.createCellStyle();
style.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
cell.setCellValue("");
cell.setCellStyle(style);
}
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
You might find that MissingCellPolicy can help with your needs. When calling getCell on a row, you can specify a MissingCellPolicy to have something happen if no cell was there, eg
Row r = sheet.getRow(2);
Cell c = r.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK);
c.setCellValue("This will always work, c will never be null");
org.apache.poi.ss.util.CellUtil can also help too:
// Get the row, creating it if needed
Row r = CellUtil.getRow(4, sheet);
// Get the cell, creating it if needed
Cell c = CellUtil.getCell(2, r);