Not able to view ComboBox in Excel using JXL API - java

I am trying to show ComboBox in JXL API with following Code:
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("DropDown1");
arrList.add("DropDown2");
arrList.add("DropDown3");
WritableCellFeatures cellFeatures = new WritableCellFeatures();
cellFeatures.setDataValidationList(arrList);
Blank b = null;
Label checkLabel = null;
for (int x = 0; x < xlData.size(); x++) {
for (int i = 0; i <= 14; i++) {
System.out.println("X:" + x + "I:" + i);
if (i > 9) {
checkLabel = new Label(i, x + xlHeader.size(),(String) arrList.get(0));
//b = new Blank(i, x + xlHeader.size());
//b.setCellFeatures(cellFeatures);
checkLabel.setCellFeatures(cellFeatures);
writableSheet.addCell(checkLabel);
System.out.println("Combo Cell : " + x + ":" + i);
}
}
}
I have tried both "Blank" Cell as well as "Label". But still the Excel is not showing ComboBox.

If you call close() without calling write() first, a completely empty file will be generated.
Once you have finished adding sheets and cells to the workbook, you call write() on the workbook, and then close the file. This final step generates the output file (output.xls in this case) which may be read by Excel. credits this excellent tutorial it's required to add:
copy.write();
copy.close();
The cellFeatures needs to be re-instantiate inside the loop
according to my tests this code works fine:
WritableCellFeatures cellFeatures = null;
Label checkLabel = null;
for (int x = 0; x < xlData.size(); x++) {
for (int i = 0; i <= 14; i++) {
System.out.println("X:" + x + "I:" + i);
if (i > 9) {
checkLabel = new Label(i, x + xlHeader.size(), (String) arrList.get(0));
cellFeatures = new WritableCellFeatures();
cellFeatures.setDataValidationList(arrList);
checkLabel.setCellFeatures(cellFeatures);
writableSheet.addCell(checkLabel);
}
}
}
// All cells modified/added. Now write out the workbook
workbook.write();
workbook.close();
Even the Blank version works but in this case the cell hasn't an initial value
according to my tests also this code works fine:
WritableCellFeatures cellFeatures = null;
Blank b = null;
for (int x = 0; x < xlData.size(); x++) {
for (int i = 0; i <= 14; i++) {
System.out.println("X:" + x + "I:" + i);
if (i > 9) {
b = new Blank(i, x + xlHeader.size());
cellFeatures = new WritableCellFeatures();
cellFeatures.setDataValidationList(arrList);
b.setCellFeatures(cellFeatures);
writableSheet.addCell(b);
}
}
}
// All cells modified/added. Now write out the workbook
workbook.write();
workbook.close();
If you open the generated file .xls with Excel 2010 or Excel 2013 you may need to save as .xlsx to see the combo.
I experienced that opening .xls by Excel2010/2013,
even if the cells actually contains a data validation list and the validation constraints works the data validation arrow are missing; that you need to save as in the new format if you want see the arrow and the combobox.
Moreover this drawback seems rather caused by the last Excel versions and not by JXL, demonstrated by the fact that opening the .xls in OpenOffice.org Cal 3.4.1 there is not any problem and the combo works correctly; this could be related to the fact that the current version jxl 2.6.12
2009-10-26 I use for the test Generates spreadsheets in Excel 2000 format
The Java code developed for this answer is available to anyone who wants to improve or fork and play with it.

Related

Reading from excel files using JAVA poi and ignoring empty cells

I was trying to read data from an excel sheet that contains empty cells consider the following code:
File src = new File(path to your file);
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheet("Sheet1");
int rowCount = sheet1.getLastRowNum();
System.out.println("total number of rows is: " + rowCount);
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
System.out.println(data);
}
However, my code also reads the empty cells and displays the value as 0 (The cells have numeric value). How do I make my script read-only cells that are filled and display them while ignoring the ones that are empty?
Thank you in advance
Just update the for loop with an if condition which will check for the value which is getting retrieved from the Cell. PFB the updated for loop.
For Apache POI version 4.x you can try below-
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
Cell cell = sheet1.getRow(i).getCell(1);
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
if(c.getCellType() == CellType.Blank)
{
continue;
}
else{
System.out.println(data);
}
}
For Apache POI version 3.x you can try below-
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
Cell cell = sheet1.getRow(i).getCell(1);
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
continue;
}
else{
System.out.println(data);
}
}

Failed to looping in a jtable in JCCD API

I have build code clone application, that using JCCD API that impelemnted ANTLR. To show the code clone, I am using a jtable. This is my screenshot Application : https://docs.google.com/file/d/0B_Rg--NnjJccMERpaTNidzR3cFE/edit?usp=sharing
Okey, from the following screenshot above, I was success to compare one file to another one file. The problem is when I am compare a file to two or more files. The tables just give me the last suspect of code clone.
But, in my netbeans output console, I was success that showed in this link : https://drive.google.com/file/d/0B_Rg--NnjJccWWdVTjdZc1R1bWc/edit?usp=sharing
How can I showed the right output console one to more files to my jTable ?
This is My code :
public static void printSimilarityGroups(final SimilarityGroupManager groupContainer) {
SimilarityGroup[] simGroups = groupContainer.getSimilarityGroups(); // output similarity groups
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable1.getModel();
model.setRowCount(0);
List<final_tugas_akhir.Report> theListData = new ArrayList<Report>();
if (null == simGroups) {
simGroups = new SimilarityGroup[0];
}
if ((null != simGroups) && (0 < simGroups.length)) {
for (int i = 0; i < simGroups.length; i++) {
final ASourceUnit[] nodes = simGroups[i].getNodes();
System.out.println("");
System.out.println("Similarity Group " + simGroups[i].getGroupId());
for (int j = 0; j < nodes.length; j++) {
final SourceUnitPosistion minPos = getFirstNodePosition((ANode) nodes[j]);
final SourceUnitPosistion maxPos = getLastNodePosition((ANode) nodes[j]);
ANode fileNode = (ANode) nodes[j];
while (fileNode.getTipe() != TipeNode.FILE.getTipe()) {
fileNode = fileNode.getParent();
}
final_tugas_akhir.Report theResult = new final_tugas_akhir.Report(); //final_tugas_akhir.Report() is a class that contain getter and setter
//Mixing the Line
StringBuilder sb = new StringBuilder();
StringBuilder append = sb.append(minPos.getBaris()).append("."); // get the row
sb.append(minPos.getKarakter()).append(" - "); //get Character
StringBuilder append1 = sb.append(maxPos.getBaris()).append(".");// get row
sb.append(maxPos.getKarakter()); get the character
theResult.setSimiliaritygroup(simGroups[i].getGroupId()); //Similiarity Group
theResult.setId(nodes[j].getId()); //setter similiarity id on token
theResult.setIndikasi(nodes[j].getText()); // setter Kind of Similairity
theResult.setFileutama(fileNode.getText()); //Files name
theResult.setLine(sb.toString());
theListData.add(theResult);
}
}
for (Report report : theListData) {
//test for the console
System.out.print(report.getSimiliaritygroup() + " ");
System.out.print(report.getId() + " ");
System.out.print(report.getIndikasi() + " ");
System.out.print(report.getFileutama() + " ");
System.out.print(report.getLine() + "\n");
//for table that failed
model.addRow(new Object[]{
report.getSimiliaritygroup(),
report.getId(),
report.getIndikasi(),
report.getFileutama(),
report.getLine()});
}
} else {
System.out.println("No similar nodes found.");
}
}
Thank you so much...

JTable FileWriter error

I'm busy with a FileWriter, and with very limited knowledge of writing text files, I found a few examples of what I need, and with that I created my own coding. I'm working in NetBeans.
The Objective:
Export JTable contents to a text file on button pressed.
The Problem:
bw.write(model.getValueAt(i, j));
The pre-error show: No suitable method found for write(Output)...
What's going on here?
This is how the process works:
1)The administrator runs the First Run Configuration
2)The administrator clicks on Add User {1}
(Apps.Settings.FTRun)
3)The administrator creates the user by entering the fields. Clicking on insert, the app creates a userid, then uploads the user to the database. ALSO, it adds the username and password to the table in FTRun.It's supposed to add the elements, but it doesn't! (Code included below)
Apps.UserManager.AddUser
4)The table doesn't populate, so I type in random strings in the table. I then click on . This throws the NullPointerException
Here's my code:
1) Export Code
2) Populate Table Code
Export Code
try {
File file = new File("C:/Program Files/DocuLoc/bin/export.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
TableModel model = jTable1.getModel();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
//Create your File Writer
bw.write(model.getValueAt(i, j));
}
}
bw.close();
JOptionPane.showConfirmDialog(this, "Table exported successfully!\nFile located at " + file);
} catch (Exception e) {
e.printStackTrace();
}
Populate Table Code
try {
Apps.Settings.FTRun ftrun = new Apps.Settings.FTRun();
DefaultTableModel model = (DefaultTableModel) ftrun.jTable1.getModel();
model.addRow(new Object[]{UploadUName, UploadPwd});
ftrun.jTable1.enableInputMethods(true);
} catch (Exception e) {
e.printStackTrace();
}
I would use:
bw.write( model.getValueAt(i, j).toString() );
which will write the String representation of any Object you might be storiung in your TableModel.
Edit:
The NPE is caused by the bw.write(model.getValueAt(i,j).toString()); line
So what is null, "bw", "model", the data from the getValue(...) method?
I'm guessing the data, in which cause you can use code like:
Object data = model.getValueAt(I, j);
if (data == null)
System.out.println("null data at - " + I + " : " + j);
else
bw.write( data.toString() );
then once you know what cell(s) are null you investigate to find out why.
None of BufferedWriter's write methods take an Object type as returned by getValueAt. You could do
bw.write((String)model.getValueAt(i, j));
Thanks to #camickr and #Reimeus for assistance in solving this!
This code shows how you write JTable contents to a text file.
If your table has values, your code should look like this:
try {
File file = new File(filePathAndFileName); //Format: C:/.../.../file.txt
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//OPTIONAL: clear the file contents. Omitting this will continue
// writing the file
PrintWriter writer = new PrintWriter(file.getAbsoluteFile());
writer.print("");
writer.close();
//Start the writing process
TableModel model = jTable1.getModel();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//Execute writer to write until all values in the table have been written
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
Object data = model.getValueAt(i, j);
bw.write(data.toString());
}
}
//OPTIONAL - If you have multiple columns and want to separate, use the
// following instead of the execution above
//FORMAT Column1 : Column2 : ...
//new line Column1 : Column2 : ...
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
Object data = model.getValueAt(i, j);
bw.write(data.toString());
//Custom coding here for the row. I used two columns
if (j == 0) {
bw.write(" : ");
} else {
}
}
bw.newLine();
}
//End the Writing Process
bw.close();
System.out.println("Writing complete");
}catch(Exception ex){
e.printStackTrace();
}

Read data from excel file

I have searched through StackOverflow, but didn't find a clear answer to my question.
I have a simple 2 columns and 24 rows xlsx (excel) file (later on this file will have more columns and rows , and also eventually it will have different sheets).
First row is header row: year=x and population=y, and for each header I want to read the rows below. Later on I want to be able to use this information to create a dynamic plot (x,y),
So I think I need to save the x and y information in variables. Below is my pseudo code.
//Sheet Pop
final String POP = "Pop";
int startRowHeader = 1,
startRowNumeric = 2,
startColNumeric = 1,
nrOfCols = 0,
nrOfRows = 0;
int nrOfSheets = excelFile.getWorkbook().getNumberOfSheets();
org.apache.poi.ss.usermodel.Sheet sheet1 = excelFile.getWorkbook().getSheetAt(0);
String[] sheets = {POP};
boolean sheetExists;
String activeSheet = "";
nrOfCols = sheet1.getRow(0).getLastCellNum();
nrOfRows = excelFile.getLastRowNum(POP);
try {
for (String sheet : sheets) {
sheetExists = false;
for (int sheetIndex = 0; sheetIndex < nrOfSheets; sheetIndex++) {
if (sheet.equalsIgnoreCase( excelFile.getWorkbook().getSheetName(sheetIndex))) {
SheetExists = true;
}
}
if (!sheetExists) {
throw new Exception("Sheet " + sheet + " is missing!");
}
}
//Take off!
// Sheet Pop
activeSheet = sheets[0];
for(int j=0; j < nrOfCols; j++) {
for(int i=0; i<nrofRows; i++) {
column[i] = (int)excelFile.getCellNumericValue(POP, startRowNumeric, startColNumeric);
}
}
} catch (Exception e) {
traceln(" ..... ");
traceln("Error in sheet: " + activeSheet);
traceln("Message: " + e.getMessage()); //Write out in console
}
create a new class:
public class Point {
int x;
int y;
}
in your main function create a
List<Point> allPoints = new List<Point>();
then add the points you read from excel to this List
do this in a loop
Point p = new Point();
p.x = xCoordinateFromExcel;
p.y = yCoordinateFromExcel;
allPoints.add(p);
also consider adding constructor and getter/setters to your Point class.
also you might want to use the Point class available in java.awt directly.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
EDIT: regarding fetching values from excel
this is what i understand from your question
you have 24 rows with 2 columns
first column has x, second column has y value
so you can just do something like this in a loop
for(int i=0;i<24;i++){
Row row = sheet.getRow(i);
Cell cellX = row.getCell(1);
Cell cellY = row.getCell(2);
//assign to point class
...
}
dont forget to parse it to int, or use getNumericCellValue()
http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getNumericCellValue()
You can use a java.util.ArrayList of java.awt.geom.Point2D.Double
Declare the list:
ArrayList<Point2D.Double> points = new ArrayList<>();
Then for each row:
// Read x
// Read y
Point2D.Double p = new Point2D.Double(x, y);
/// And add to the list:
points.add(p);

POI Appending .0 while reading numeric data from excel

I am using POI HSSF to read excel data and I am using JUnit to check the data against database proc RefCursor.
The Junit test fails as the numeric data from the Refcursor for example 100 are compared against the data in the excel sheet 100 but it fails as the POI reads it as 100.0.
InputStream fileInputStream = Testdb.class.getClassLoader().getResourceAsStream(fileName);
//retrieve number of columns and rows
int numRows=0, numCols=0, i, j, minColIndex=0, maxColIndex=0;
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
Iterator rowIterator = hssfSheet.rowIterator();
while (rowIterator.hasNext())
{
numRows++;
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTempList = new ArrayList();
if (numRows == 1)
{
minColIndex = hssfRow.getFirstCellNum();
maxColIndex = hssfRow.getLastCellNum();
numCols = maxColIndex;
}
for(int colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell hssfCell = hssfRow.getCell(colIndex);
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
String expected[][] = new String[numRows][numCols];
String[] tableColumns = new String[numCols];
System.out.println("Rows : " + numRows + "Columns : " + numCols);
System.out.println("Min Col Index : " +minColIndex + "Max Col Index : " + maxColIndex);
for (i=0; i<numRows; i++)
{
List cellTempList = (List) cellDataList.get(i);
for (j=0; j < numCols; j++)
{
HSSFCell hssfCell = (HSSFCell) cellTempList.get(j);
if (i == 0)
{
tableColumns[j] = hssfCell.toString();
System.out.print(tableColumns[j] + "\t");
}
else
{
if(hssfCell != null)
{
expected[i-1][j] = hssfCell.toString();
}
else
{
expected[i-1][j] = null;
}
System.out.print(expected[i-1][j] + "\t");
}
}
System.out.println();
}
This is a generic framework program which I am building so the framework should be intelligent enough to disregard the ".0".
Any inputs on how to resolve this?
This is virtually identical to a number of other questions here, such as returning decimal instead of string (POI jar)
The answer is the same as the one I gave here:
POI is giving you the exact value that Excel has stored in the File. Generally, if you write a number in an Excel cell, Excel will store that as a number with formatting. POI provides support to do that formatting for you if you want it (most people don't - they want the numbers as numbers so they can use them)
The class you're looking for is DataFormatter. Your code would be something like
DataFormatter fmt = new DataFormatter();
for (Row r : sheet) {
for (Cell c : r) {
CellReference cr = new CellRefence(c);
System.out.println("Cell " + cr.formatAsString() + " is " +
fmt.formatCellValue(c) );
}
}
Hi my solution was just to put the symbol:
'
in front of every number. Then the number is processed as text.
After you do that you would see little green triangle and warning:
For me this is not a problem, because it works.

Categories

Resources