Imported data only showing in first column in JTable (Java) - java

I tried to make a simple GUI where I can add the First/Last Name of a person and their date of birth. After adding the data to the JTable I can save it in a TxT File and Load it back into the JTable again.
Part where Data is saved:
private void saveListener(){
jb1.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showSaveDialog(PeopleGUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) { // Datei Explorer
try {
File file = fileChooser.getSelectedFile();
PrintWriter o = new PrintWriter(file); // o steht für Output
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.print(peopleModel.getColumnName(col) + ";");
}
o.println("");
for (int row = 0; row < peopleModel.getRowCount(); row++) {
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.println(peopleModel.getValueAt(row, col));
}
}
o.close();
// Output in der Konsole
System.out.println("Success!");
} catch (IOException c) {
c.printStackTrace();
}
}
});
}
Part where Data is loaded:
public void loadListener() {
jb2.addActionListener(e -> {
final JFileChooser fileChooser = new JFileChooser();
int response = fileChooser.showOpenDialog(PeopleGUI.this);
if (response == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader br = new BufferedReader(new FileReader("jlist.txt"));
// Erste Linie sind Kolonnen Beschriftungen
String firstLine = br.readLine().trim();
String[] columnsName = firstLine.split(";");
DefaultTableModel model = (DefaultTableModel) peopleList.getModel();
model.setColumnIdentifiers(columnsName);
// Daten vom TxT holen
Object[] tableLines = br.lines().toArray();
// Reihen mit Daten
for (int i = 0; i < tableLines.length; i++) {
String line = tableLines[i].toString().trim();
String[] dataRow = line.split("/");
model.addRow(dataRow);
}
}
catch (IOException b) {
b.printStackTrace();
}
}
});
}
The problem is, that the imported data is only showing in the first row:
This is how it looks right now
Does anyone now how to fix this issue?
Thanks in advance!

The problem is how you save your data to a file
for (int row = 0; row < peopleModel.getRowCount(); row++) {
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.println(peopleModel.getValueAt(row, col));
}
}
Here you save each cell of the JTable in a new line. You want to save each row in a new line with values separated by /
for (int row = 0; row < peopleModel.getRowCount(); row++) {
String r = "";
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
r += peopleModel.getValueAt(row, col);
if (col < peopleModel.getColumnCount() - 1) {
r += "/";
}
}
o.println(r);
}
EDIT: As #camickr stated use StringJoiner is better
for (int row = 0; row < peopleModel.getRowCount(); row++) {
StringJoiner stringJoiner = new StringJoiner("/");
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
stringJoiner.add(peopleModel.getValueAt(row, col).toString());
}
o.println(stringJoiner.toString());
}

Related

how to read data from excel, having only one column

//method contains:
public Object[][] getExcelData(String excelLocation) {
Object[][] dataSet = null;
try {
file = new FileInputStream(excelLocation);
wrkbook = new XSSFWorkbook(file);
wrkbook.close();
sheet = wrkbook.getSheetAt(0);
// to get total active row count
int rowNum = sheet.getLastRowNum();
// to get total active column count
int colNum = sheet.getRow(0).getLastCellNum();
dataSet = new Object[rowNum][colNum];
for (int i = 0; i <rowNum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j <=colNum; j++) {
XSSFCell cell = row.getCell(j);
String value = String.valueOf(cell);
dataSet[i][j] = value;
}
}
return dataSet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
// return null if for any exception
If you want to return the column values from the spreadsheet as a 2d array, change the signature of your method to return an array of type String[][], iterate over each row of the spreadsheet, adding the value of all of its columns to the array, and return the Array when you're done. I haven't tested this but it should be pretty close:
public static String[][] getDataSetAsArray(XSSFSheet pSheet) {
int iRowCount = pSheet.getLastRowNum();
int iColumnCount = pSheet.getRow(pSheet.getFirstRowNum()).getLastCellNum();
String[][] strDataVals = new String[iRowCount][iColumnCount];
for (int r = 0; r <= iRowCount; r++) {
XSSFRow row = pSheet.getRow(r);
for (int c = 0; c <= iColumnCount; c++) {
strDataVals[r][c] = row.getCell(c).getStringCellValue();
}
}
return strDataVals;
}

How to remove entire row basis of a String in the cell in apache POI

I am working on a xlsx file which contains two last rows in the end , i have to excluse the rows on the basis of the cell values it contains.i.e My excel contains Total India(10%) and Total(10%) in its last two rows so i have to exclude the two rows on a basis of Total keyword. I am using the following approach but its not working
#Override
public List<String> processSheet(Sheet sheet) {
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " started");
List<String> rows = new ArrayList<String>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
StringBuilder row = new StringBuilder();
for (int i = 0; i < currentRow.getLastCellNum(); i++) {
if(currentRow.getRowNum()==0 || currentRow.getRowNum()==1|| currentRow.getRowNum()==2|| currentRow.getRowNum()==3|| currentRow.getRowNum()==4|| currentRow.getRowNum()==5|| currentRow.getRowNum()==6|| currentRow.getRowNum()==7|| currentRow.getRowNum()==9|| currentRow.getRowNum()==10|| currentRow.getRowNum()==11) {
continue;
}else {
Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = excelManager.evalCell(currentCell);
if (!cellValue.isEmpty()) {
row.append(cellValue);
}
// trying to remove the rows containing total --------------------------------------->
int rowNums = sheet.getPhysicalNumberOfRows();
for(int k =0;k<rowNums;k++) {
currentRow = sheet.getRow(k);
if(currentRow !=null) {
for(int j=0;j<currentRow.getLastCellNum();j++) {
currentCell = currentRow.getCell(j);
if(currentCell !=null && currentCell.getCellTypeEnum().equals(CellType.STRING) && currentCell.getStringCellValue().toLowerCase().contains("total")){
sheet.removeRow(currentRow);
rowNums++;
}
}
}
}
//---------------------------------------------------------->
//adjusting the cell values with the | or BLANK
if(currentCell == null || currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
row.append("");
}else {
row.append(SEPARATOR);
}
}
}
if (!row.toString().isEmpty()) {
rows.add(row.toString());
}
}
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " completed");
return rows;
}
}
Can anyone help ??
This is my little test program. It removes every row that contains the word total. You will have to remove the code that you don't need (first 2 and last line probably)
XSSFWorkbook wb = new XSSFWorkbook(new File("test.xlsx"));
XSSFSheet sheet = wb.getSheetAt(0);
int rowNums = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rowNums; i++) {
XSSFRow r = sheet.getRow(i);
if (r != null) {
for (int j = 0; j < r.getLastCellNum(); j++) {
XSSFCell c = r.getCell(j);
if (c != null && c.getCellTypeEnum().equals(CellType.STRING)
&& c.getStringCellValue().toLowerCase().contains("total")) {
sheet.removeRow(r);
rowNums++;
}
}
}
}
wb.write(Files.newOutputStream(Paths.get("test2.xlsx"), StandardOpenOption.CREATE_NEW));
Updated for your code:
List<String> rows = new ArrayList<String>();
int rowNums = sheet.getPhysicalNumberOfRows();
for (int k = 0; k < rowNums; k++) {
Row currentRow = sheet.getRow(k);
if (currentRow != null) {
StringBuilder row = new StringBuilder();
for (int i = 0; i < currentRow.getLastCellNum(); i++) {
if (currentRow.getRowNum() <= 11 && currentRow.getRowNum() != 8) {
continue;
} else {
Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = excelManager.evalCell(currentCell);
if (!cellValue.isEmpty()) {
row.append(cellValue);
}
if (currentCell != null && currentCell.getCellTypeEnum().equals(CellType.STRING)
&& currentCell.getStringCellValue().toLowerCase().contains("total")) {
sheet.removeRow(currentRow);
rowNums++;
}
if (currentCell == null || currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
row.append("");
} else {
row.append(SEPARATOR);
}
}
}
if (!row.toString().isEmpty()) {
rows.add(row.toString());
}
}
}

how can I "refresh" my table, so that I could display same table with different data?

How can I "refresh" my table, so that I could display same table with different data?
String columnNames[] = {"First Name", "Last Name", "Phone Number", "E-mail"};
JTable contactTable = new JTable(data, columnNames);
jScrollPane = new JScrollPane(contactTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
where is your data saved ?
i save it in a text file and use this way to refresh my data but you need a button to refresh every time
here is my code
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// Refresh Button
try {
for (int r = 0; r < 100; r++) { //initializing row
for (int c = 0; c < 4; c++) { //initializing column
jTable1.setValueAt(null, r, c);
}
}
BufferedReader rdfile = new BufferedReader(new FileReader("items.txt"));
String[] item = new String[100];
String[] temp;
int x = 0; //read item
while ((item[x] = rdfile.readLine()) != null) {
temp = item[x].split("\t");
jTable1.setValueAt((1000 + x + 1), x, 0);
for (int j = 1; j < 4; j++) {
jTable1.setValueAt(temp[j - 1], x, j);
}
x++;
}
rdfile.close();
} catch (IOException e) {
}
}

Setting the color and formatting of cell when using Apache Poi does not work

I have been thinking of days for the solution. Anyway, I am doing a program where the apache will copy the whole sheet to another sheet in a workbook. Currently, my code can copy the contents but not the colour and format of the sheet. Please assist as I really unsure on how to proceed. Thanks.
int rowReadIndent = 0;
int columnReadIndent = 0;
int rowWriteIndent = 0;
int columnWriteIndent = 0;
ArrayList<ArrayList<ArrayList<Object>>> lists = new ArrayList<ArrayList<ArrayList<Object>>>();
ArrayList<ArrayList<ArrayList<Short>>> cellColorLists = new ArrayList<ArrayList<ArrayList<Short>>>();
//ArrayList<ArrayList<ArrayList<XSSFCellStyle>>> cellStyleLists = new ArrayList<ArrayList<ArrayList<XSSFCellStyle>>>();
ArrayList<String> sheetNameList = new ArrayList<String>();
for(int i = 0; i < fileArrayList.size(); i++) {
OPCPackage pkg = OPCPackage.open(new FileInputStream(desktop + "/test/" + fileArrayList.get(i)));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Sheet sheet1 = wb.getSheetAt(0);
lists.add(new ArrayList<>());
//cellStyleLists.add(new ArrayList<ArrayList<XSSFCellStyle>>());
cellColorLists.add(new ArrayList<>());
sheetNameList.add(sheet1.getSheetName());
for(int j = 0; j < 50; j++) {
Row row1 = sheet1.getRow(j + rowReadIndent);
lists.get(i).add(new ArrayList<>());
//cellStyleLists.get(i).add(new ArrayList<XSSFCellStyle>());
cellColorLists.get(i).add(new ArrayList<>());
if(row1 != null) {
for(int k = 0; k < 50; k++) {
Cell cell1 = row1.getCell(k + columnReadIndent, Row.RETURN_BLANK_AS_NULL);
if(cell1 != null){
Object o = null;
int type = cell1.getCellType();
if(type == Cell.CELL_TYPE_FORMULA) {
type = cell1.getCachedFormulaResultType();
}
switch (type) {
case Cell.CELL_TYPE_STRING:
o = cell1.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell1)) {
o = cell1.getDateCellValue();
} else {
o = cell1.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
o = cell1.getBooleanCellValue();
break;
}
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle.cloneStyleFrom(cell1.getCellStyle());
//cellStyleLists.get(i).get(j).add(cellStyle);
XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
cellStyle = (XSSFCellStyle) cell1.getCellStyle();
cellColorLists.get(i).get(j).add(cellStyle.getFillBackgroundColor());
lists.get(i).get(j).add(o);
}
else {
lists.get(i).get(j).add(null);
}
}
}
}
pkg.close();
}
OPCPackage pkg1 = OPCPackage.open(new FileInputStream(desktop + "/test/Output Graph.xlsx"));
XSSFWorkbook wb1 = new XSSFWorkbook(pkg1);
FileOutputStream stream = new FileOutputStream(desktop + "/Output Graph4.xlsx" /*+ name + ".xlsx"*/);
for(int i = 0; i < lists.size(); i++) {
Sheet sheet1 = wb1.createSheet();
wb1.setSheetName(wb1.getSheetIndex(sheet1), sheetNameList.get(i));
for(int j = 0; j < lists.get(i).size(); j++) {
Row row1 = sheet1.createRow(j + rowWriteIndent);
for(int k = 0; k < lists.get(i).get(j).size(); k++) {
Cell cell1 = row1.createCell(k + columnWriteIndent);
//cell1.setCellStyle(cellStyleLists.get(i).get(j).get(k));
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle = (XSSFCellStyle) cell1.getCellStyle();
//cellStyle.setFillBackgroundColor(cellColorLists.get(i).get(j).get(k));
if(lists.get(i).get(j).get(k) != null) {
switch (lists.get(i).get(j).get(k).getClass().getSimpleName()) {
case "String":
cell1.setCellValue((String)lists.get(i).get(j).get(k));
break;
case "Date":
cell1.setCellValue((Date)lists.get(i).get(j).get(k));
break;
case "Double":
cell1.setCellValue((Double)lists.get(i).get(j).get(k));
break;
case "Boolean":
cell1.setCellValue((Boolean)lists.get(i).get(j).get(k));
break;
}
}
}
}
}
/* Sheet sheet1;
Row row1;
Row row2;
Cell cell1;
for(int j = 0; j < lists.size(); j++) {
wb1.cloneSheet(0);
sheet1 = wb1.getSheetAt(j+1);
row1 = sheet1.createRow(1);
row2 = sheet1.createRow(0);
for(int i = 0; i < lists.get(j).size(); i++) {
cell1 = row1.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
//cell1.setCellValue(lists.get(j).get(i));
System.out.println("Stored: "+lists.get(j).get(i));
}
for(int i = 0; i < lists1.get(j).size(); i++) {
cell1 = row2.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
cell1.setCellValue(lists1.get(j).get(i));
System.out.println("Stored: "+lists1.get(j).get(i));
}
}*/
wb1.write(stream);
stream.close();
pkg1.close();
Desktop.getDesktop().open(new File(desktop + "/Output Graph4.xlsx"));
} catch (FileNotFoundException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
}
}

Writing 2d array into file that needs to look like array

I have the following code that creates and writes to the file but it writes everything out in one solid line.
Example: 11111111111111111111111111
I need it look like the following(space in between every number):
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Here is my code:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This is because you are not putting space between them.
bw.write(String.valueOf(gameArray[row][col]));
bw.write(" ");
and at the end of inner loop, again,
bw.write("\n");
write bw.write("\n") at the end of your inner loop.
Just like :
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write("\n")
}
This should work for you:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]);
if ((col+1)!=gameArray[row].length)
bw.write(" ");
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write(System.getProperty("line.seperator"));
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Categories

Resources