how to read xls file into jtable - java

Im having trouble with importing XLS data to jtable.
My program reads only the last row from XLS.
Here is my code:
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
Stavka stavka = new Stavka();
File f = new File(excelPath);
Workbook wb = null;
try {
wb = Workbook.getWorkbook(f);
}
catch (BiffException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++) {
for (int j = 0; j < col; j++) {
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
//System.out.println(c.getContents());
}
// this is my tableModel
lista.add(stavka);
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}
}
How can this be fixed?

I believe the error exists because you must create a new Stavka object for each line in your XLS, and then add it to 'lista'. Finally, I believe you also want to set the model (TabelaStavka) outside these for loops.
I don't have a full Java environment installed here, so forgive me if there is any syntax error below. The most important thing is that you understand what are the fixes you have to do in your code.
Also, never underestimate code formatting, you should consider using a better IDE, which helps out better formatting your source code.
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
File f = new File(excelPath);
Workbook wb = null;
try
{
wb = Workbook.getWorkbook(f);
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++)
{
Stavka stavka = new Stavka(); // new instance <<<<<<<<
for (int j = 0; j < col; j++)
{
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
}
lista.add(stavka); // inside second for loop <<<<<<<<
}
// outside the second for loop <<<<<<<<<<<<<<<<<<<<<<<<<<
// this is my tableModel
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}

Related

Imported data only showing in first column in JTable (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());
}

Java Swing and Excel [duplicate]

This question already has answers here:
How to read and write excel file
(22 answers)
Closed 5 years ago.
I am trying to write the data from table format to to Excel sheet,during this date is shown as "#######" in excel.But while i increasing the cell size the date is visible correctly.So i want to increase the width size of the excel file from the code itself.Is anyone can help me ?The code is below`
JButton btnExport = new JButton("Export To Excel");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
btnExport.setMnemonic(KeyEvent.VK_X);
btnExport.addActionListener(new AksyonListener());
}
public void toExcel(JTable table1, File file) {
try {
System.out.println("Success");
FileWriter excel = new FileWriter(file);
// DefaultTableModel model = new DefaultTableModel();
// table.setModel(model);
// model.insertRow(table.getRowCount(), new Object[]{0});
for (int i = 0; i < table.getColumnCount(); i++) {
excel.write(table.getColumnName(i) + "\t");
System.out.println(table.getColumnName(i));
}
/* int d,f;
System.out.println("d: "+table.getRowCount());
System.out.println("f: "+table.getColumnCount());*/
excel.write("\n");
for (int i = 1; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
excel.write(table.getValueAt(i, j) + "\t");
System.out.println(table.getValueAt(i, j));
}
excel.write("\n");
}
excel.close();
} catch (IOException e) {
System.out.println(e);
}
}
class AksyonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnExport) {
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(TableSortFilter.this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4) {
ext = filename.substring(len - 4, len);
}
if (ext.equals(".xls")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xls";
}
toExcel(table, new File(file));
}
}
}
}
});
Try to use apache poi to export and create excel
https://poi.apache.org/

Trying to extract data and write to another spreadsheet comes up empty

The output file is created but only the first cell is written and nothing else. I tested it with system print and all the data that I want shows up in console but is not written to the worksheet.
public class excel_read_2 {
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("C:/Users/h.M/Desktop/20151007-110016_outgoing.xls")); //input
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("C:/Users/h.M/Desktop/workbook.xls"); //output
int rowcounter = 0;
for (int rowNum = 150; rowNum < 180; rowNum++) {
Row r = sheet.getRow(rowNum);
if (r == null) {
continue;
}
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getStringCellValue());
System.out.println("The cell was a string \" " + c.getStringCellValue()+" \" ");
} else if (c.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getNumericCellValue());
System.out.println("The cell was a number " + c.getNumericCellValue());
}
}
rowcounter++;
}
wb.write(fileOut);
fileOut.close();
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Create the new row before you loop, then use it once per loop.
Row row = sheet1.createRow((short)rowcounter);
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Cell cell = row.createCell(cn);
cell.setCellValue(c.getStringCellValue());

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

reading desired data from file but saving the whole file data

I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX

Categories

Resources