Jtable to Excel in Java - java

I created a registration form, that collects data from user, and display it into a Jtable, then I want to allow user to press a button to export the Jtable content to excel form. In the display table, it can show all user input, but when I export to excel, it only show columnNames and first row of data, so I want to know if I have done it wrong?
User input:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
String[] columnNames = new String[] {"First Name", "Last Name", "Email", "Degree", "Year", "Event"};
Object[][] tabledata = new Object[1][6];
String fn = FirstName.getText();
String ln = LastName.getText();
String em = Email.getText();
String re = ReEnter.getText();
String de = Degree.getSelectedItem().toString();
String yr = Year.getSelectedItem().toString();
String ev = EventDate.getSelectedItem().toString();
ArrayList<String> data = new ArrayList<String>();
data.add(fn);
data.add(ln);
data.add(em);
data.add(de);
data.add(yr);
data.add(ev);
list.add(data);
//Set fields to empty
FirstName.setText("");
LastName.setText("");
Email.setText("");
ReEnter.setText("");
Degree.setSelectedItem(null);
Year.setSelectedItem(null);
EventDate.setSelectedItem(null);
// print data to table
Object[][] temp = new Object[tabledata.length+1][6];
for(int i=0;i<tabledata.length;i++){
for(int j=0;j<6;j++){
temp[i][j] = tabledata[i][j];
}
temp[tabledata.length-1][0]= fn;
temp[tabledata.length-1][1]= ln;
temp[tabledata.length-1][2]= em;
temp[tabledata.length-1][3]= de;
temp[tabledata.length-1][4]= yr;
temp[tabledata.length-1][5]= ev;
}
tabledata = temp;
table.setModel(new DefaultTableModel(tabledata, columnNames));
}
}
Export data to excel:
try {
TableModel model = table.getModel();
File file = new File("member.xls");
FileWriter output = new FileWriter(file);
for(int i = 0; i <model.getColumnCount(); i++){
output.write(model.getColumnName(i) + "\t");
}
output.write("\n");
for(int k=0;k<model.getRowCount();k++) {
for(int j=0;j<model.getColumnCount();j++) {
output.write(model.getValueAt(k,j).toString()+"\t");
}
output.write("\n");
output.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
![Run program] [1]: http://i.stack.imgur.com/T99L5.png
![Exported excel file][2]: http://i.stack.imgur.com/ZGy3Z.png

Check your bracketing :P
You call output.close() inside the first for-loop for printing out data. This closes the file before getting to the 2nd row and onwards.

Related

How do i find the mean and median through a csv using an array on a Jframe?

I'm just a tad bit confused, I need to find the median and mode through this code through an array and I want to input it into a textfield since i'm using Jframes.
This is the code i'm using for the actual CSV document, it already reads the files from the CSV, but the mean and median bit is a bit confusing...
public void theSearch() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Joshua\\Desktop\\Data Set.csv")));
//BufferedReader br = new BufferedReader(new FileReader(new File("H:\\2nd Year\\Programming Group Project\\Data Set.csv")));
List<String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
setMinimumSize(new Dimension(640, 480));
String[] columnNames = new String[] {
"Reporting period", "Period of coverage", "Breakdown", "ONS code", "Level", "Level description", "Gender", "Indicator value", "CI lower", "CI upper", "Denominator", "Numerator"
};
Object[][] content = new Object[elements.size()][13];{
for(int i=1; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0];
content[i][1] = elements.get(i)[1];
content[i][2] = elements.get(i)[2];
content[i][3] = elements.get(i)[3];
content[i][4] = elements.get(i)[4];
content[i][5] = elements.get(i)[5];
content[i][6] = elements.get(i)[6];
content[i][7] = elements.get(i)[7];
content[i][8] = elements.get(i)[8];
content[i][9] = elements.get(i)[9];
content[i][10] = elements.get(i)[10];
content[i][11] = elements.get(i)[11];
content[i][12] = elements.get(i)[12];
}
};
jTable.setModel(new DefaultTableModel(content,columnNames));
jScrollPane2.setMinimumSize(new Dimension(600, 23));
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
add(jScrollPane2);
//TableModel model = new DefaultTableModel (content, columnNames);
//JTable jTable = new JTable(model);
//jTable.setPreferredScrollableViewportSize(new Dimension(1200, 400));
// TableRowSorter<TableModel> sorted = new TableRowSorter <TableModel>(model);
// jTable.setRowSorter(sorted);
// jTable.setEnabled(false);
// JScrollPane pane = new JScrollPane(jTable);
System.out.println(jTable.getModel().getValueAt(1, 1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
To calculate statistics such as mean and median you need to have numbers rather than strings. So the first thing you need to do is to convert the strings you are reading from the file into the appropriate data type. By far the best way to do this in Java is to create a class to represent objects in each row and then turn your rows into a collection of those objects.
I'm not sure what your rows represent so I'll just call the class Row here:
class Row {
private final int reportingPeriod;
private final int level;
...
public Row(String[] values) {
this.reportingPeriod = Integer.valueOf(values[0]);
this.level = Integer.valueOf(values[1]);
...
}
public int getLevel() {
return level;
}
}
List<Row> rows = new ArrayList<>();
while((line = br.readLine())!=null) {
rows.add(new Row(line.split(","));
}
Or in Java 8:
List<Row> rows = br.lines().map(l -> new Row(l.split(","))).collect(toList());
To find the median and mean:
int[] levels = new int[rows.size()];
int sum = 0;
for (int i = 0; i < rows.size(); i++) {
levels[i] = rows.get(i).getLevel();
sum += levels[i];
}
Arrays.sort(levels);
int median = levels[rows.size() / 2];
double mean = (double)sum / rows.size();
In Java 8 this would be:
int median = rows.stream().mapToInt(Row::getLevel).sorted().skip(rows.size() / 2).findFirst().get();
double mean = rows.stream().mapToInt(Row::getLevel).average().getAsDouble();

How Can I populate a JTable from an excel file, as long as there is more than 1 matching element in my Array List? [Java]

[![enter image description here][1]][1]I'm having a problem populating a JTable from an excel file. Here is the operation, I will search, lets say "Line 1", there are 2 cells matching this value, if there is a match, I would like to pull the row and insert it into my JTable. I was able to get this working, however, this only creates one row for the first matching value, when i click on search button again, it will replace the row, with a new row, if there was more than 1 match.
I would the jtable to add both rows in the same table, rather one by one. I attached what I have so far.
Thank You in advanced.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(LinNum_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
DefaultTableModel model = new DefaultTableModel();
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
model.addColumn("ID", new Object[] { val_0 });
model.addColumn("Date", new Object[] { val_1 });
model.addColumn("Auditor Name", new Object[] { val_2 });
model.addColumn("Line #", new Object[] { val_3 });
table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I was able to get this working, however, this only creates one row for the first matching value,
That is because in your "looping code" you create a new JTable each time.
Instead you want to create the table once and add data to your TableModel inside the loop. So the structure of your code should be something like:
String[] columnNames = { "Id", "Date", ... };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (...)
{
...
if (matched row found)
{
...
Object[] row = { val_0, val_1, ...};
model.addRow( row );
}
JTable table = new JTable( model );
...
With camickr's help I got this to work. Here is the final code.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
String[] columnNames = {"Id","Date","Auditor Name","Line Number"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(Spec_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
Object[] ROWS = { val_0, val_1, val_2,val_3};
model.addRow( ROWS );
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

Display JSON data in a ComboBox using java

I used the code below to retrieve json data and put it in a table. That worked. But I want to display the data in a combobox now. Right now, it is displaying the items in the dropdown in this format: ljava.lang.string #5c647e05
Can someone please tell me what I'm doing wrong? Thank you.
Hashtable response = parser.parse(reader);
java.util.List allResult = (java.util.List) response.get("AllResult");
System.out.println(allResult);
try {
String[][] data = new String[allResult.size()][4];
for (int i = 0; i < allResult.size(); i++) {
Object obj = allResult.get(i);
String result = (String) ((Hashtable) obj).get("Status");
String investorName = (String) ((Hashtable) obj).get("investorName");
if (result.equalsIgnoreCase("ok")) {
for (int j = 0; j < 4; j++) {
if (j == 0) {
data[i][j] = investorName; }
}
}
}
ComboBox investorNames = new ComboBox(data);
details.addComponent(investorNames);
System.out.println("Data here: " + data);
String[] columnNames = { "Seller's Name", "Stock Name", "Unit", "Price" };
TableModel model = new DefaultTableModel(columnNames, data, false);
Table table = new Table(model);
table.setScrollable(true);
details.addComponent(table);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Try to paste in Combobox only vector of invector names not whole array of arrays. As Combobox just invokes toString() on every array (row) of matrix, that's why you got Ljava.lang.String#5c647e05 and not investor names. Something like this:
String[] comboData = new String[allResult.size()];
for (int i = 0; i < allResult.size(); i++){
...
String investorName = (String) ((Hashtable) obj).get("investorName");
comboData[i] = investorName
...
}
ComboBox investorNames = new ComboBox(comboData);
details.addComponent(investorNames);
....
ComboBox expects an array of string but you are passing to it an array of array of strings.
So those ljava.lang.string #5c647e05 that you are seeing are the 'toString' representation of an array of strings.
You need to somehow (depending on what you need to do) flatten your 'data' so that it becomes an array of strings.

Problems with default table model

I am creating java editable table, and faced to problem: it "crashes" after reading data. Here is my table:
table.getTableHeader().setReorderingAllowed(false);
tableModel = new DefaultTableModel(new Object[]
{"#","1","2","3","4","5","6","7"},8);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
Reading from txt:
OK4.addActionListener(new ActionListener(){
#Override
File f = new File(fileName);
if(f.exists()){
try {
tableModel = new DefaultTableModel(new Object[]{"#","1","2","3","4","5","6","7"},0);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
String[] data = line.split("\\s+");
tableModel.addRow(data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null, "this day is not saved");
};
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
});
And main problems causing my sum field:
OK3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int sum=0;
int number;
Object smth;
String Smth;
int kint2 = table.getRowCount()-1;
if(table.getValueAt(kint2, 1)=="total:"){
}else{
tableModel.addRow(new Object[]{});
int a = table.getRowCount()-1;
table.setValueAt("total:", a, 1);
}
for (int j = 2; j < 8; j++) {
for (int i = 0; i < table.getRowCount()-1; i++) {
smth = table.getValueAt(i,j);
Smth = (String) smth;
if (smth==null){
number=0;
}else{
number=Integer.parseInt(Smth);
}
sum=sum+number;
}
table.setValueAt(sum, table.getRowCount()-1, j);
sum=0;
}
}
});
Application stops calculate sum after being read from txt or calculates only first 4 rows sum. Have it something to do with my tableModel?
Thank you for answers.
The problem is that you add new rows with tablemodel and count rows with table. As discussed at "jTable row count VS model row count" your table won't update the rows count so always use tablemodel.getRowCount()

Populating jtable from array under a loop

On each loop, it collects info from a certain file and stores it's contents in an array. The array should then create a new row per loop on the table. My problem is, is that it only creates 1 row. How can I fix this?
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
iCount = humanReadableByteCount(listOfFiles[i].length(), true);
if (files.toLowerCase().endsWith(".mp3"))
{
//jTextArea1.append("File name: " + files + " | Last Modified: " + sdf.format(listOfFiles[i].lastModified()) + " | Lenght: " + iCount + "\n");
Object rowData[] = { files, sdf.format(listOfFiles[i].lastModified()), iCount };
Object columnNames[] = { "Name", "Last Modified", "Size" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
model.addRow(rowData);
jTable1.setModel(model);
}
}
}
Create the model outside the loop. Set the table model outside the loop as well.
The only thing to do inside the loop is to add the new rows to the model.
You create a new model every time you cycle the loop. So every time, you have a new and empty model and you add 1 row to the empty model.
It should be like this:
Object columnNames[] = { "Name", "Last Modified", "Size" };
DefaultTableModel model = new DefaultTableModel(columnNames);
jTable1.setModel(model);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".mp3"))
{
files = listOfFiles[i].getName();
iCount = humanReadableByteCount(listOfFiles[i].length(), true);
model.addRow(new Object[]{ files, sdf.format(listOfFiles[i].lastModified()), iCount });
}
}

Categories