how to add images in HSSFCell in apache POI? - java

How to add Image in different different HSSFCell object in poi ?
I have written some code which is adding image but problem is, the cell were I added last image, That cell only showing image other than that no other cells are showing images ...
appreciate your help ...
My Code is
while(rs.next()){
HSSFCell cell = getHSSFCell(sheet, rowNo, cellNo);
cell.setCellValue(new HSSFRichTextString(rs.getString("TEST_STEP_DETAILS")) );
cell.setCellStyle(style);
String annotate = rs.getString("ANNOTATE");
if(annotate != null){
int index = getPicIndex(wb);
HSSFPatriarch patriarch=sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(400,10,655,200,(short)cellNo,(rowNo+1),(short)cellNo,(rowNo+1));
anchor.setAnchorType(1);
patriarch.createPicture(anchor, index);
}
cellNo++;
}
getPicIndex METHOD :-
public static int getPicIndex(HSSFWorkbook wb){
int index = -1;
try {
byte[] picData = null;
File pic = new File( "C:\\pdf\\logo.jpg" );
long length = pic.length( );
picData = new byte[ ( int ) length ];
FileInputStream picIn = new FileInputStream( pic );
picIn.read( picData );
index = wb.addPicture( picData, HSSFWorkbook.PICTURE_TYPE_JPEG );
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return index;
}

i hope you found the solution yourself. if not:
the problem is that you create for every image a new partiarch.
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
you should create only one patriarch instance and use its createPicture method for all images.

Related

Update excel using Java

I am trying to update a column in the excel sheet but only the first row is getting update. The second iteration is not working. Could anyone help me on this? Below is my code that I am trying.
String excelPath = "path";
String YES = "Updated YES";
String NO = "Updated NO";
try {
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
Cell cell = null;
FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
HSSFSheet sheet1 = workSheet.getSheetAt(0);
String data = sheet1.getRow(i+1).getCell(i).toString();
if(data.equals(TCID.get(i))){
cell = sheet1.getRow(i+1).getCell(i+2);
cell.setCellValue(YES);
workSheet.write(output_file);
}else {
cell.setCellValue(NO);
workSheet.write(output_file);
}
}
fis.close();
output_file.close();
workSheet.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My latest code is below. Now it is updating the columns but the last row is not getting updated. What am i missing.
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet1 = workSheet.getSheetAt(0);
//FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
}
fis.close();
//output_file.close();
//workSheet.close();
FileOutputStream output_file =new FileOutputStream(excelPath);
workSheet.write(output_file);
output_file.close();
The row and the column are both keyed off 'i', so you'll be traversing the sheet diagonally.
But certainly do the things the other people are recommending too, they are all good suggestions.
Typically when working with a two dimensional block of information, I find it useful to have one loop for rows and then nested inside that a loop for columns (or vice versa)
e.g.
for (y = startRow; y <= maxRow; y++) {
....
for (x = startCol; x <= maxCol; x++) {
.... // do something to each column in the current row
cell = sheet1.getRow(y).getCell(x);
.....
Ok, so there are a couple of things.
Declare HSSFSheet sheet1 = workSheet.getSheetAt(0); outside of your loop. You are working with the same sheet each iteration of your for loop, so this only has to be invoked once.
Your logic to get the cell data (String data = sheet1.getRow(i+1).getCell(i).toString();) will not return you the same column. On your first iteration, you'll get (R)ow 1 : (C)olumn 0. The next iteration will return R2 : C1, then R2:C2, then R3:C3, etc. Notice the pattern that you are going diagonally down the columns, not vertically.
Rows start at 0.
You only need to workSheet.write(output_file); once you have done all your processing.
If the Row does not exist you will get a NullPointerException
As you are working with a unique Cell each iteration, you just declare it in the loop (so no need for Cell cell = null; outside your loop).
Here is a an example:
try {
FileInputStream fis = new FileInputStream(excelPath);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < 5; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(0);
cell.setCellValue("Updated cell.");
}
}
FileOutputStream output_file = new FileOutputStream(excelPath);
workbook.write(output_file);
output_file.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
I think moving Cell reference inside for loop should fix it for you.
Cell cell = null;
Also you might also need to move outside if-block incase you face NullPointerException in else-block
cell = sheet1.getRow(i+1).getCell(i+2)
Something like this...
HSSFSheet sheet1 = workSheet.getSheetAt(0);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
workSheet.write(output_file)
}

Why can't set a value for a row and column with the Apache POI?

I need to set a value for a specific row and column of the spreadsheet, but I get a null pointer before even i = 1. I've tried changing the code but this error keeps happening and I have no more idea why.Does anyone have any idea why this happens?
My code
public Workbook build(Planilha planilha) {
File file = new File(TEMPLATE_PATH);
if (!file.exists()) {
Log.error(this, String.format("File %s not exists.", file.getAbsolutePath()));
throw new NotFoundException("File not exists.");
}
Workbook wb = null;
try (FileInputStream fs = new FileInputStream(file)) {
wb = new XSSFWorkbook(fs);
wb = writeMetadatas(planilha, wb);
Map<String, Integer> header = getHeader(wb);
Sheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
for (int i = 0; i <= 10; i++) {
row = sheet.getRow(i);
for (int j = 0; j <= 10; j++) {
cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
if (cell.getColumnIndex() == 0 && row.getRowNum() == 7) {
cell.setCellValue("teste");
}
}
}
} catch (Exception e) {
Log.error(this, "Erro: Planilha não existe", e);
System.err.print("Erro");
}
String tmpDir = System.getProperty("java.io.tmpdir");
File f = FileUtil.file(PATH, System.currentTimeMillis() + ".xlsx");
try {
FileOutputStream fout = new FileOutputStream(f);
wb.write(fout);
fout.flush();
fout.close();
} catch (Exception e) {
Log.error(this, "Erro ao abrir arquivo p escrever.");
}
return wb;
}
**NullPointer happens in cell.setCellValue("teste");
I'm trying to set that cell
First, you can test if the row number is a certain number outside of your for loop that loops over the cells in a row. Pull that if outside your j for loop.
It looks like the Cell doesn't exist. row.getCell(j) is returning null.
You can use a MissingCellPolicy to determine whether you want to return a new Cell if the Cell doesn't already exist. The CREATE_NULL_AS_BLANK value will create a blank Cell for you if it doesn't already exist.

Locating a cell image

I have inserted an image in an Excel table successfully; but now I have a huge trouble, I want the images to be centered in a single cell, since when I export the file with the images, they seems to be inside one cell., but when I look closely the image is some millimeters our of the cell which makes difficult to work. The image doesn't recognize which cell it belong to. using the library of Apache POI.
I hope you can help me, thanks.
here I send you part of the code,
int posReporte = 1;
int posRow = 1;
for (List<Object> dr : datosReportes) {
Row filaReporte = hojaReporte.createRow(posReporte);
for (int a = 0; a < dr.size(); a++) {
Cell celdaD = filaReporte.createCell(angel);*
celdaD.setCellStyle(estiloDatos);
Object obj = dr.get(angel);
if (a == 0) {
hojaReporte.setColumnWidth(a, 180 * 38);
filaReporte.setHeight(Short.valueOf("1500"));
//Add image data to the book
try {
if (directorio("S:\\", dr.get(1) + "_mini")) {
InputStream is = new FileInputStream("S:\\" + dr.get(1) + "_mini.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
CreationHelper helper = wb.getCreationHelper();
Drawing drawing = hojaReporte.createDrawingPatriarch();
//Add image
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(o);
anchor.setRow1(posRow);
anchor.setAnchorType(o);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
}
} catch (Exception e) {
continue;
}
}
}
}

Apache poi. Formula evalution. evaluteAll vs setForceFormulaRecalculation

[better quality]:. http://imageshack.us/photo/my-images/51/v5cg.png/
Problem: i use formulas in my workBook.xlsx. Depending on the circumstances i change value (3,3). At this example i changed 10 to 20. And after that i want to calculate the formula, which use this cell. When it has finished, it will override the value of the cells, remove formula and record the value. This cell no longer be used for the calculations again.
Code:
public class ReaderXlsx {
public List<List<String>> ReaderXlsx(String sfilename, int firstColumn, int columnsCount, int rowsCount, int moduleCount){
int lastColumn=firstColumn+columnsCount;
List<List<String>> rowsContent = new ArrayList<List<String>>();
try ( FileInputStream fileInputStream = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xlsx");)
{
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workBook.getSheetAt(0);
int firstRow = findOneInFirstColumn(sheet,50);
setModuleCount(sheet,moduleCount);
workBook.getCreationHelper().createFormulaEvaluator().evaluateAll();
toNewLine:
for (int lineId=firstRow;lineId<rowsCount;lineId++) {
List<String> columnsContent = new ArrayList<String>();
Row row = sheet.getRow(lineId);
if (row==null){continue toNewLine;}
if (row.getCell(2)==null || row.getCell(2).getStringCellValue().equals("") ) {continue toNewLine;}
for (int columnId=firstColumn+1;columnId<lastColumn;columnId++) {
Cell cell = row.getCell(columnId-1);
if ((cell==null)) { continue toNewLine;}
cell.setCellType(Cell.CELL_TYPE_STRING);
if ((columnId==0 & cell.getStringCellValue().equals(""))) {continue toNewLine;}
if ((columnId==5 & cell.getStringCellValue().equals("")) || (columnId==6 & cell.getStringCellValue().equals(""))) cell.setCellValue("0");
columnsContent.add(cell.getStringCellValue());
}
rowsContent.add(columnsContent);
}
try(FileOutputStream out = new FileOutputStream("C:\\Users\\student3\\Used"+sfilename+".xlsx"); ) {
workBook.write(out);
out.close(); }
}
catch (IOException e) {
e.printStackTrace();
}
return rowsContent;
}
private Integer findOneInFirstColumn(XSSFSheet sheet, Integer maxRows){
int result=0;
toNextLine:
for (int lineId=0;lineId<maxRows;lineId++){
Row row = sheet.getRow(lineId);
if (row==null | row.getCell(0)==null) {result++; continue toNextLine; }
else{
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
if (row.getCell(0).getStringCellValue().equals("1")){return result;}
else {result++;}
}
}
return result;
}
private void setModuleCount(XSSFSheet sheet, Integer moduleCount){
Row row = sheet.getRow(1);
if (moduleCount==0) {}
if (moduleCount>0) {row.createCell(2).setCellValue(moduleCount.toString());}
}
}
Now i use 2 files, because i need to save my formulas. I want to use only 1 (source) and update it correctly.

How Do I Create a New Excel File Using JXL?

I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.
After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found:
try {
String fileName = "file.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));
workbook.createSheet("Sheet1", 0);
workbook.createSheet("Sheet2", 1);
workbook.createSheet("Sheet3", 2);
workbook.write();
workbook.close();
} catch (WriteException e) {
}
I know that it's a very old question. However, I think I can contribute with an example that also adds the cell values:
/**
*
* #author Almir Campos
*/
public class Write01
{
public void test01() throws IOException, WriteException
{
// Initial settings
File file = new File( "c:/tmp/genexcel.xls" );
WorkbookSettings wbs = new WorkbookSettings();
wbs.setLocale( new Locale( "en", "EN" ) );
// Creates the workbook
WritableWorkbook wwb = Workbook.createWorkbook( file, wbs );
// Creates the sheet inside the workbook
wwb.createSheet( "Report", 0 );
// Makes the sheet writable
WritableSheet ws = wwb.getSheet( 0 );
// Creates a cell inside the sheet
//CellView cv = new CellView();
Number n;
Label l;
Formula f;
for ( int i = 0; i < 10; i++ )
{
// A
n = new Number( 0, i, i );
ws.addCell( n );
// B
l = new Label( 1, i, "by" );
ws.addCell( l );
// C
n = new Number( 2, i, i + 1 );
ws.addCell( n );
// D
l = new Label( 3, i, "is" );
ws.addCell( l );
// E
f = new Formula(4, i, "A" + (i+1) + "*C" + (i+1) );
ws.addCell( f );
}
wwb.write();
wwb.close();
}
}
First of all you need to put Jxl Api into your java directory , download JXL api from http://www.andykhan.com/ extract it,copy jxl and paste like C:\Program Files\Java\jre7\lib\ext.
try {
String fileName = "file.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));
WritableSheet writablesheet1 = workbook.createSheet("Sheet1", 0);
WritableSheet writablesheet2 = workbook.createSheet("Sheet2", 1);
WritableSheet writablesheet3 = workbook.createSheet("Sheet3", 2);
Label label1 = new Label("Emp_Name");
Label label2 = new Label("Emp_FName");
Label label3 = new Label("Emp_Salary");
writablesheet1.addCell(label1);
writablesheet2.addCell(label2);
writablesheet3.addCell(label3);
workbook.write();
workbook.close();
} catch (WriteException e) {
}
Not sure if you need to stick with JXL, but the best library for handling Excel files is Apache's POI HSSF.
I think there are plenty of examples on the website I provided, but if you need further assistence, let me know. I may have a few examples laying around.
Just out of curiosity, POI stands for Poor Obfuscation Interface and HSSF is Horrible SpreadSheet Format. You see how much Apache loves Microsoft Office formats :-)
public void exportToExcel() {
final String fileName = "TodoList2.xls";
//Saving file in external storage
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/javatechig.todo");
//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
workbook = Workbook.createWorkbook(file, wbSettings);
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("MyShoppingList", 0);
Cursor cursor = mydb.rawQuery("select * from Contact", null);
try {
sheet.addCell(new Label(0, 0, "id")); // column and row
sheet.addCell(new Label(1, 0, "name"));
sheet.addCell(new Label(2,0,"ff "));
sheet.addCell(new Label(3,0,"uu"));
if (cursor.moveToFirst()) {
do {
String title =cursor.getString(0) ;
String desc = cursor.getString(1);
String name=cursor.getString(2);
String family=cursor.getString(3);
int i = cursor.getPosition() + 1;
sheet.addCell(new Label(0, i, title));
sheet.addCell(new Label(1, i, desc));
sheet.addCell(new Label(2,i,name));
sheet.addCell(new Label(3,i,family));
} while (cursor.moveToNext());
}
//closing cursor
cursor.close();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories