Generate Excel using Apache POI - java

I have generated an excel (.xls) document using Apache POI. I use HSSF classes.
Could someone advise me on the following question:
How can we keep the column headers in the diaplay part constant and have scroll only on the data part?
That is, I want the header columns to be always visible when the excel file is scrolled down.
Thanks,
David

One option may be the repeating rows suggestion from timboo. Not sure on your exact needs, but it's possible you might want a Freeze Pane instead.
To have the first row always on screen, never scrolling off, you'd do:
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("No Scroll");
sheet1.createFreezepane(0,1);
You can freeze rows, columns or both, see this javadoc or this for details

Check out the Apache POI Busy Developers Guide:
It's possible to set up repeating rows and columns in your printouts
by using the setRepeatingRowsAndColumns() function in the HSSFWorkbook
class.
This function Contains 5 parameters. The first parameter is the index
to the sheet (0 = first sheet). The second and third parameters
specify the range for the columns to repreat. To stop the columns from
repeating pass in -1 as the start and end column. The fourth and fifth
parameters specify the range for the rows to repeat. To stop the
columns from repeating pass in -1 as the start and end rows.
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
// Set the columns to repeat from column 0 to 2 on the first sheet
wb.setRepeatingRowsAndColumns(0,0,2,-1,-1);
// Set the the repeating rows and columns on the second sheet.
wb.setRepeatingRowsAndColumns(1,4,5,1,2);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

This should help you. I've searched for days and found this. This solved my problem.
`Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet("new sheet");
Row row = sheet1.createRow((short) 0);
// Create a cell and put a value in it.
row.createCell(0).setCellValue(
createHelper.createRichTextString("Freeze"));
for (int i = 1; i < 20; i++) {
row = sheet1.createRow((short) i);
row
.createCell(0)
.setCellValue(
createHelper
.createRichTextString("This is the Moving Row"));
}
// Freeze just one row
sheet1.createFreezePane(0, 1, 0, 1);`

Related

Java - merge two excel sheets into one

I need to merge two sheets into one.
Eg. I have excel file test.xls with two sheets, sheet0 and sheet1. Both sheets have some text and table.
I would like to merge them so merged sheet would look like this:
text from sheet0
table from sheet0
text from sheet1
table from sheet1
I need to do this in Java.
Is there a simple way to do this?
Something like :
HSSFWorkbook book = new HSSFWorkbook("/tmp/test.xls");
HSSFSheet sheet0 = book.getSheetAt(0);
HSSFSheet sheet1 = book.getSheetAt(1);
sheet0.merge(sheet1); //or combine or something
Didn't find such method in Poi API
Otherwise, you can manually append the content of sheet1 into sheet0 like :
int lastRowNum1 = sheet1.getLastRowNum();
int i=0;
int currentLinePos=sheet0.getLastRowNum();
while ( i <= lastRowNum1 ){
Row currentRow = sheet1.getRow(i++);
Row copiedRow = sheet0.createRow(currentLinePos++);
// code that copy the content of currentRow into copiedRow
// such as copying every cells
// or try copiedRow = currentRow; but not sure it will copy the cells
}

How to add header column in excel using Java Apache POI?

I am writing a java program in which I have to take data from XML file and put it into excel file. While doing this I have to create row headers and add data accordingly.
I know how to create column headers. I can do it in following way:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Header1");
header.createCell(1).setCellValue("Header2");
header.createCell(2).setCellValue("Header3");
header.createCell(3).setCellValue("Header4");
....
It creates excel file as shown below:
But I want my excel file looks like below:
I am not getting a way to do this. It's not good idea to create required number of rows individually. Is there any way by which we can create a column and add all header in that column?
The way I tried to do this is:
....
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("EDR Raw Data");
sheet.createRow(0).createCell(0).setCellValue("header1");
sheet.createRow(1).createCell(0).setCellValue("header2");
sheet.createRow(2).createCell(0).setCellValue("header3");
sheet.createRow(3).createCell(0).setCellValue("header4");
...
But in my case I have to give 100+ row labels. SO this won't be efficient way.
Just create one row for each header, and populate the first cell in each!
Something like:
String[] headers = new String[] { "Header1", "Header2", "Header3" };
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("EDR Raw Data");
for (int rn=0; rn<headers.length; rn++) {
Row r = sheet.createRow(rn);
r.createCell(0).setCellValue(headers[rn]);
}
Then when populating your data, do sheet.getRow(rownumber) to get the existing row, and populate the remaining cells of interest in it

Reading data from xlsx with Apache POI's SXSSFSheet

I want to read data ( cell values ) from a certain xlsx file using apachi poi.
The code below creates the SXSSFWorkBook instance successfully and assigns db.xlsx ( my dummy xlsx). I have tried changing sheet numbers and double checking it with the getSheetNumber method to make sure the workbook is correctly assigned.
Next I want to assign a specific sheet (index 0 with name main) to SXSSFSheet instance, but currently it returns null. (I have both tried getSheetAt and getSheet methods).
SXSSFRow DummyRow;
SXSSFCell DummyCell;
int RowCount;
OPCPackage pkg = OPCPackage.open(blabla string adress);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Workbook MainBook = new SXSSFWorkbook(wb,100);
int a = MainBook.getNumberOfSheets();
SXSSFSheet MainSheet = (SXSSFSheet) MainBook.getSheetAt(0);
RowCount = MainSheet.getLastRowNum();
What am I doing wrong?
Edit:
I have tried getSheetName method and had a positive result. So the problem is with reaching rows in Worksheet. so, the last line getLastRowNum() is not working.
You can't. SXSSFWorkBook is write only, it doesn't support reading
For low memory reading of .xlsx files, you should look at the XSSF and SAX EventModel documentation

Changing cell format with Apache POI causes loss of data and unexpected behavior.

I am using Apache POI to create, access and modify *.xlsx and *.xls files. I got stuck on changing cell formats(don't confuse with styles).
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(100); // setting cell value with double makes it numeric -> 100 aligned to the right
cell.setCellType(1); // changing cell format to text -> 100.0 aligned to the left
cell.setCellType(0); // changing cell format back to numeric -> 0 aligned to the right
FileOutputStream fos = new FileOutputStream("test.xlsx");
wb.write(fos);
One may think that changing between text and numeric format causes the data to be replaced with 0. However trying the same thing for more cells gives some more unexpected results:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
for(int i=0;i<10;i++){
Row row = sheet.createRow(i);
for(int j=0;j<10;j++){
Cell cell = row.createCell(j);
cell.setCellValue(i*j);
cell.setCellType(1);
cell.setCellType(0);
}
}
FileOutputStream fos = new FileOutputStream("test.xlsx");
wb.write(fos);
The expected output is Multiplication table. Well... it's not. Actually changing the range of i and j affects the results for the same cell addresses.
Is this a bug in Apache POI?
Maybe it's due to OOXML specification and it's actually Microsofts mistake?
Or is something wrong with my computer and your output files look like they should?

How to initialize cells when creating a new Excel file (Apache POI)

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

Categories