Set position of comment-tooltip in xls-file using Apache POI - java

I try to add a comment to a excel-field.
If I open the excel-file using Excel97 the Tooltip has bad boundings.
public static void main(String[] args) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("Test1");
HSSFCreationHelper ch = sheet.getWorkbook().getCreationHelper();
HSSFClientAnchor anchor = ch.createClientAnchor();
HSSFComment comment = sheet.createDrawingPatriarch().createCellComment(anchor);
comment.setRow(0);
comment.setColumn(1);
comment.setString(ch.createRichTextString("Test2"));
comment.setAuthor("RM");
cell.setCellComment(comment);
sheet.autoSizeColumn(0);
workbook.close();
workbook.write(new FileOutputStream("d:/test.pdf"));
}
How to set the size of the tooltip programatically?

You should add comment along the lines of the example in Busy Developers' Guide to HSSF and XSSF Features.
Using the ClientAnchor position settings (col1, dx1, row1, dy1, col2, dx2, row2, dy2) you can set the position of the comment box.
Example:
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelWithComments {
public static void main(String[] args) throws Exception {
String type = "HSSF";
//String type = "XSSF";
Workbook wb = ("HSSF".equals(type))?new HSSFWorkbook():new XSSFWorkbook();
CreationHelper factory = wb.getCreationHelper();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0); // cell A1
cell.setCellValue("A1");
Drawing drawing = sheet.createDrawingPatriarch();
// When the comment box is visible, have it show in a 1x3 space
ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(cell.getColumnIndex()+1); // starts at column A + 1 = B
anchor.setDx1(("HSSF".equals(type))?10*15:10*Units.EMU_PER_PIXEL); // plus 10 px
anchor.setCol2(cell.getColumnIndex()+2); // ends at column A + 2 = C
anchor.setDx2(("HSSF".equals(type))?10*15:10*Units.EMU_PER_PIXEL); // plus 10 px
anchor.setRow1(row.getRowNum()); // starts at row 1
anchor.setDy1(("HSSF".equals(type))?10*15:10*Units.EMU_PER_PIXEL); // plus 10 px
anchor.setRow2(row.getRowNum()+3); // ends at row 4
anchor.setDy2(("HSSF".equals(type))?10*15:10*Units.EMU_PER_PIXEL); // plus 10 px
// Create the comment and set the text+author
Comment comment = drawing.createCellComment(anchor);
RichTextString str = factory.createRichTextString("Hello, World!");
comment.setString(str);
comment.setAuthor("Apache POI");
// Assign the comment to the cell
cell.setCellComment(comment);
String fname = ("HSSF".equals(type))?"./comment-xssf.xls":"./comment-xssf.xlsx";
try (OutputStream out = new FileOutputStream(fname)) {
wb.write(out);
}
wb.close();
}
}
Result:

Related

Getting date in double format 43318.4847916667 instead of 06-08-2018 11:38:06

I am writing a java code to generate an excel file using HSSFWorkbook(.xls). I need to write date in one column in this format 06-08-2018 11:38:06 but it is generating like this 43318.4847916667.
Here is the code snippet i used.
Please help me how can i successfully write
Workbook workbook = new HSSFWorkbook();
Sheet excelSheet = workbook.createSheet();
Row dataRow = excelSheet.createRow(1);;
Cell dataCell = dataRow.createCell(1);;
CellStyle cStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
cStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
dataCell.setCellValue(new Date());
dataCell.setCellStyle(cStyle);
Cannot reproduce the problem.
The following complete example results in an Excel workbook having a worksheet and a proper formatted date in cell B2.
Code:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelDate {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xls") ) {
CellStyle cStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
cStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
Sheet excelSheet = workbook.createSheet();
Row dataRow = excelSheet.createRow(1);;
Cell dataCell = dataRow.createCell(1);;
dataCell.setCellValue(new java.util.Date());
dataCell.setCellStyle(cStyle);
excelSheet.setColumnWidth(1, 25 * 256);
workbook.write(fileout);
}
}
}
Result:
From your comment it turns out that your question does not show the whole. There is a loop for rows and for each row a date shall be created. And that only works up to 42nd row.
Well that problem is well known. Excel has a limit for the count of cell styles per workbook. See: Excel specifications and limits.
So, if you create a new cell style over and over in the loop, that limit is sometimes reached. However, you do not always have to create new cell styles in the loop. Cell styles are stored at workbook level. Just create any needed cell style once outside the loop. Then apply only the previously created cell styles to the cell within the loop.
The following works for me and creates 1000 proper formatted dates:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelDate {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xls") ) {
CellStyle cStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
cStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
Sheet excelSheet = workbook.createSheet();
for (int r = 1; r < 1000; r++) {
Row dataRow = excelSheet.createRow(r);;
Cell dataCell = dataRow.createCell(1);;
dataCell.setCellValue(new java.util.GregorianCalendar(2019, 9, r));
dataCell.setCellStyle(cStyle);
}
excelSheet.setColumnWidth(1, 25 * 256);
workbook.write(fileout);
}
}
}
If you want "06-08-2018 11:38:06" then your dateformat should be "dd-MM-YYYY HH:mm:ss". Otherwise you are just missing the FileOutputStream which you need to write the workbook to.
private static final String FILE_NAME = "./out/MyFirstExcel.xls";
public static void main(String ... args) {
Workbook workbook = new HSSFWorkbook();
Sheet excelSheet = workbook.createSheet();
Row dataRow = excelSheet.createRow(1);
Cell dataCell = dataRow.createCell(1);
CellStyle cStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
cStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-YYYY HH:mm:ss"));
dataCell.setCellValue(new Date());
dataCell.setCellStyle(cStyle);
try {
File file = new File(FILE_NAME);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Follow below code for printing date in DD-MM-YYYY HH:MM:ss.
String fileName = "myExcel.xls";
WritableWorkbook writableWorkbook = null;
response.setContentType("application/vnd.ms-excel");
writableWorkbook = Workbook.createWorkbook(response.getOutputStream());
WritableSheet excelOutputsheet = writableWorkbook.createSheet("Sheet1", 0);
DateFormat customDateFormatWithTime = new DateFormat("dd-MM-yyyy HH:mm:ss");
WritableCellFormat dateFormatWithTime = new
WritableCellFormat(customDateFormatWithTime);
int row = 0;
int col = 0;
excelOutputsheet.setColumnView(col, 20);
Label lable1 = new Label(col, row, "Date and Time", cellFormat);
excelOutputsheet.addCell(lable1);
row = row + 1;
col = col + 1;
DateTime myDate = new jxl.write.DateTime(col, row, "Value", dateFormatWithTime);
excelOutputsheet.addCell(myDate);

Apache POI - is there a way to create a pivot table where the source table is a SXSSFSheet?

This is the case:
I have to use SXSSFWorkbook (Streaming version of XSSFWorkbook) to create my Excel, because I have to create a sheet with 700000/800000 rows with about 20 columns. This sheet represents the source table for my final Pivot.
SXSSFWorkbook workbook();
XSSFSheet pivotSheet = workbook.getXSSFWorkbook().createSheet("Pivot sheet");
AreaReference ar = ....:
CellReference cr = ....;
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(ar, cr); // ERROR!!
The problem is that, when I try to create this Pivot on that source, the XSSFPivotTable.createPivotTable method not work, despite AreaReference and CellReference arguments are ok.
If I use XSSFWorkbook (not streaming version) with less rows, all is ok, but I do not reach my goal!
Can someone give me a solution? Thank you very much!!!!!
Stefano
SXSSFWorkbook can be created from XSSFWorkbook.
So what I would do is creating XSSFWorkbook having a XSSFSheet with at least the headings of the data and another XSSFSheet for the pivot table. Then creating the XSSFPivotTable on this XSSFSheet but making the reference to the data sheet big enough for later data.
Then I would creating the SXSSFWorkbook from this XSSFWorkbook, getting the data sheet as SXSSFSheet and then streaming the big amount of data into the data sheet.
Complete example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.xssf.streaming.*;
import java.util.Random;
import java.io.FileOutputStream;
class SXSSFPivotTableTest {
private static void streamCellData(Sheet sheet, int rowsCount) {
for (int r = 1; r <= rowsCount; r++) {
Row row = sheet.createRow(r);
Cell cell = row.createCell(0);
cell.setCellValue("Name " + ((r-1) % 4 + 1));
cell = row.createCell(1);
cell.setCellValue(r * new java.util.Random().nextDouble());
cell = row.createCell(2);
cell.setCellValue(r * new java.util.Random().nextDouble());
cell = row.createCell(3);
cell.setCellValue("City " + ((r-1) % 3 + 1));
}
}
public static void main(String[] args) throws Exception{
int rowsCount = 1000000;
//first create XSSFWorkbook
XSSFWorkbook wb = new XSSFWorkbook();
//create XSSFSheet with at least the headings
XSSFSheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("Value1");
cell = row.createCell(2);
cell.setCellValue("Value2");
cell = row.createCell(3);
cell.setCellValue("City");
//create XSSFSheet for pivot table
XSSFSheet pivotSheet = wb.createSheet("Pivot sheet");
//create pivot table
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(
new AreaReference(new CellReference("Sheet1!A1"),
new CellReference("Sheet1!D" + (rowsCount +1)), //make the reference big enough for later data
SpreadsheetVersion.EXCEL2007),
new CellReference("A5"));
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
//Avarage the third column
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
//Add filter on forth column
pivotTable.addReportFilter(3);
//now create SXSSFWorkbook from XSSFWorkbook
SXSSFWorkbook swb = new SXSSFWorkbook(wb);
SXSSFSheet ssheet = swb.getSheet("Sheet1");
//now stream the big amount of data to build the pivot table on into Sheet1
streamCellData(ssheet, rowsCount);
swb.write(new FileOutputStream("SXSSFPivotTableTest.xlsx"));
swb.close();
swb.dispose();
}
}

Can I traverse through an excel file using Indexes when working with Apache POI?

Please excuse me if I am not clear. English is not my first language.
I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?
public static void main(String[] args) throws IOException {
File myFile = new File("temp.xlsx");
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#SuppressWarnings("resource")
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String comment = cell.toString();
if (comment.equals("Comments"))
{
System.out.println("Hello");
}
}
}
}
For the question "Wanted to go to the second column's 3rd row I could use coordinates like (3, 2)?":
Yes this is possible using CellUtil. Advantages over the methods in Sheet and Row are that CellUtil methods are able getting the cell if it exists already or creating the cell if it not already exists. So existing cells will be respected instead simply new creating them and so overwriting them.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.concurrent.ThreadLocalRandom;
public class CreateExcelCellsByIndex {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
//put content in R3C2:
Cell cell = CellUtil.getCell(CellUtil.getRow(3-1, sheet), 2-1); //-1 because apache poi's row and cell indexes are 0 based
cell.setCellValue("R3C2");
//put content in 10 random cells:
for (int i = 1; i < 11; i++) {
int r = ThreadLocalRandom.current().nextInt(4, 11);
int c = ThreadLocalRandom.current().nextInt(1, 6);
cell = CellUtil.getCell(CellUtil.getRow(r-1, sheet), c-1);
String cellcontent = "";
if (cell.getCellTypeEnum() == CellType.STRING) {
cellcontent = cell.getStringCellValue() + " ";
}
cell.setCellValue(cellcontent + i + ":R"+r+"C"+c);
}
workbook.write(new FileOutputStream("CreateExcelCellsByIndex.xlsx"));
workbook.close();
}
}
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING: ... break;
case NUMERIC: ... break;
case BOOLEAN: ... break;
case FORMULA: ... break;
default: data.get(new Integer(i)).add(" ");
}
}
i++;
}
I'm not sure what you mean by 2D index, but a Cell knows which column it belongs to so something like this should work:
...
Cell cell = cellIterator.next();
String comment = cell.toString();
int sourceColumnIndex = -1;
if (comment.equals("Comments")) {
System.out.println("Hello");
sourceColumnIndex = cell.getColumnIndex();
}
....
Similarly, define something like int targetColumnIndex to represent the column which will have the result from processing all the cells from the sourceColumnIndex column.

How to disable intermediate total using apache poi

How to disable intermediate total using Apache poi, I'm using apache poi for this, i want intermediate total should be disabled
Here is input in excel for understanding
Expected result
public class ApacheCreatePivotTable
{
public static void main(String[] args) throws Exception
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
// System.out.println(sheet.getRow(0).getLastCellNum());
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(new CellReference(0,0),new CellReference(4,sheet.getRow(0).getLastCellNum()-1)), new CellReference(0,7));
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setAxis(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).getItems().addNewItem().setT(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType.DEFAULT);
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
public static void setCellData(XSSFSheet sheet)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("falility");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("date");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("cost");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("tom");
Cell cell22 = row2.createCell(1);
cell22.setCellValue("Nal stop");
Cell cell23 = row2.createCell(2);
Calendar cal = Calendar.getInstance();
cal.set(2017,07,18);
cell23.setCellValue(sdf.format(cal.getTime()));
Cell cell24 = row2.createCell(3);
cell24.setCellValue(10);
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Ram");
Cell cell32 = row3.createCell(1);
cell32.setCellValue("Vadgao");
Cell cell33 = row3.createCell(2);
cal.set(2017,07,19);
cell33.setCellValue(sdf.format(cal.getTime()));
Cell cell34 = row3.createCell(3);
cell34.setCellValue(12);
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue("Deccan");
Cell cell43 = row4.createCell(2);
cal.set(2017,07,20);
cell43.setCellValue(sdf.format(cal.getTime()));
Cell cell44 = row4.createCell(3);
cell44.setCellValue(11);
Row row5 = sheet.createRow(4);
Cell cell51 = row5.createCell(0);
cell51.setCellValue("tom");
Cell cell52 = row5.createCell(1);
cell52.setCellValue("baner");
Cell cell53 = row5.createCell(2);
cal.set(2017,07,18);
cell53.setCellValue(sdf.format(cal.getTime()));
Cell cell54 = row5.createCell(3);
cell54.setCellValue(20);
}
}
Please help me with it.
As far as I see, your main requirement is getting rid of the subtotals. This is possible using org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField.setDefaultSubtotal(false).
This was asked also here Apache POI XSSFPivotTable setDefaultSubtotal.
With your example:
import java.io.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class ApacheCreatePivotTable
{
public static void main(String[] args) throws Exception
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
//System.out.println(sheet.getRow(0).getLastCellNum());
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(new CellReference(0,0),new CellReference(4,sheet.getRow(0).getLastCellNum()-1)), new CellReference(0,7));
pivotTable.addRowLabel(0);
//set tabular layout instead of tree layout
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setOutline(false);
/*
Apache poi adds 5 pivot field items of type "default" (<item t="default"/>) here.
This is because there are 5 rows (A1:C5) and, because they don't have a look at the data,
they are assuming max 5 different values. This is fine because Excel will rebuild its pivot cache while opening.
But if we want changing defaults, then this is not fine. Then we must know what items there are.
So we need at least as much items, as where different ones in the data, as numbered items: <item x="0"/><item x="1"/>
And we must build a cache definition which has shared elements for those items.
*/
for (int i = 0; i < 3; i++) {
//take the first 3 items as numbered items: <item x="0"/><item x="1"/>
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).unsetT();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).setX((long)i);
}
for (int i = 4; i > 2; i--) {
//remove further items
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().removeItem(i);
}
//set new items count
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().setCount(3);
//build a cache definition which has shared elements for those items
//<sharedItems><s v="tom"/><s v="Ram"/><s v="Terk"/></sharedItems>
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("tom");
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("Ram");
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldList().get(0).getSharedItems().addNewS().setV("Terk");
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setDefaultSubtotal(false);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setAxis(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL);
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).getItems().addNewItem().setT(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType.DEFAULT);
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
public static void setCellData(XSSFSheet sheet)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("falility");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("date");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("cost");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("tom");
Cell cell22 = row2.createCell(1);
cell22.setCellValue("Nal stop");
Cell cell23 = row2.createCell(2);
Calendar cal = Calendar.getInstance();
cal.set(2017,07,18);
cell23.setCellValue(sdf.format(cal.getTime()));
Cell cell24 = row2.createCell(3);
cell24.setCellValue(10);
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Ram");
Cell cell32 = row3.createCell(1);
cell32.setCellValue("Vadgao");
Cell cell33 = row3.createCell(2);
cal.set(2017,07,19);
cell33.setCellValue(sdf.format(cal.getTime()));
Cell cell34 = row3.createCell(3);
cell34.setCellValue(12);
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue("Deccan");
Cell cell43 = row4.createCell(2);
cal.set(2017,07,20);
cell43.setCellValue(sdf.format(cal.getTime()));
Cell cell44 = row4.createCell(3);
cell44.setCellValue(11);
Row row5 = sheet.createRow(4);
Cell cell51 = row5.createCell(0);
cell51.setCellValue("tom");
Cell cell52 = row5.createCell(1);
cell52.setCellValue("baner");
Cell cell53 = row5.createCell(2);
cal.set(2017,07,18);
cell53.setCellValue(sdf.format(cal.getTime()));
Cell cell54 = row5.createCell(3);
cell54.setCellValue(20);
}
}
Changings to your code are commented.
Result in Excel:

How to loop through all the rows and cells in an excel file

I want to use foreach to iterate through all the cells in my excel file in order to set a single foreground color. This is what I have so far.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
sheet = wb.getSheetAt(0);
for (HSSFRow myrow : sheet){
for (HSSFCell mycell : myrow){
//set foreground color here
}
}
The problem is for the statements for (HSSFRow myrow : sheet) and for (HSSFCell mycell : myrow) I am getting:
Can only iterate over an array or an instance of java.lang.Iterable
I checked HSSFSheet and HSSFRow - they implement java.lang.Iterable(Row) and java.lang.Iterable(Cell) respectively.
Try this. It compiles ok
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
sheet = wb.getSheetAt(0);
for (Row myrow : sheet) {
for (Cell mycell : myrow) {
//set foreground color here
}
}
I am using POI 3.7 Stable
Please consider using stream for a more declarative style iteration:
Workbook wb = WorkbookFactory.create(new FileInputStream("filename.xlsx"));
Sheet sheet = wb.getSheetAt(0);
StreamSupport.stream(sheet.spliterator(), false)
.filter(...)
.map(...)
.collect(Collectors.toList());
You can also use a common for-loop:
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
final Row row = sheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
final Cell cell = row.getCell(j);
// do stuff to each cell here...
}
}
Here is what I did to keep the things in simplest possible way - to loop through all rows and columns :
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelTest {
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
// Read input file
FileInputStream fis = new FileInputStream("sample.xlsx");
XSSFWorkbook wbook = new XSSFWorkbook(fis);
XSSFSheet sheet = wbook.getSheetAt(0);
// formatter for all your data to string (in this example) from date/number etc
DataFormatter formatter = new DataFormatter();
// Below code is self explanatory
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Since I needed only five columns, I hardcoded the column numbers
System.out.println(formatter.formatCellValue(row.getCell(0)));
System.out.println(formatter.formatCellValue(row.getCell(1)));
System.out.println(formatter.formatCellValue(row.getCell(2)));
System.out.println(formatter.formatCellValue(row.getCell(3)));
System.out.println(formatter.formatCellValue(row.getCell(4)));
}
}
}
Disclaimer: I used the latest POI as on date:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>

Categories

Resources