Anyone have an idea how to insert data to existing excel file from jtable am using java to develop this program and my scenario is like this, jtable data insert to excel but the excel already have a design and formula. I don't know how to start it so I ask question. thank you for your tip.
Excel uses a complicated formatting for its native .xls files but it also supports other formats. I am using the Tab-Separated Values (TSV), which is commonly used for transferring information from a database program to a spreadsheet.
You can use below code to extract data from Jtable and export it to excel.
public void toExcel(JTable table, File file) {
try {
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for (int i = 0; i < model.getColumnCount(); i++) {
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i, j).toString() + "\t");
}
excel.write("\n");
}
excel.close();
} catch (IOException e) {
System.out.println(e);
}
}
First you need to extract data from JTable. You this method:
public Object[][] getTableData (JTable table) {
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
tableData[i][j] = dtm.getValueAt(i,j);
return tableData;
}
Now having data you can append them into excel file using apache poi. Here are tutorials http://poi.apache.org/spreadsheet/quick-guide.html
Related
This is NetBeand GUI code. I need help with that specifically.
How do I get this code to append whole row in witch the asked element is to TextArea:
String trener1 = jTextField9.getText();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
int mCol = model.getColumnCount();
int mRow = model.getRowCount();
for(int i = 0; i < mCol; i++){
for(int j = 0; j < mRow; j++){
if(jTable1.getModel().getValueAt(i, j).equals(trener1)){
jTextArea1.append(model.getValueAt(i).toString()+ "\n");
}
}
}
Code should do: I have a list of gym members. Informations about them are in table, their name, age, instructor. When I type the name of the instructor in one TextField, I want all names of members that have that instructor to get appended to TextArea.
Same with their age.
That's it. Solved.
String trener1 = jComboBox5.getSelectedItem().toString();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
int Row = model.getRowCount();
for(int i = 0; i < Row; i++){
if(jTable1.getModel().getValueAt(i, 8).equals(trener1)){
jTextArea1.append(model.getValueAt(i, 1).toString());
}
}
Using apache.poi, I am trying to read an Excel sheet and using the below code, I am printing all the values inside Excel..
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
// Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
// Print Excel data in console
String location = (row.getCell(j).getStringCellValue()+ "");
System.out.println(location);
}
When I print the location System.out.println(location);, it prints my all Excel sheet data. I haven't any control over there. I am trying divide the value by the column.
Suppose I have 3 cells and I want to get a value like firstname[],lastname[],age[] so that I can do any operation by the indexing. I am not getting any solution.
Here is my full code
https://codeshare.io/anNwy3
Create a 2D String array. When iterating store the contents into the array
String[][] excelData = new String[numColumns][searcsheet.getLastRowNum()];
//numColumns is the number of columns in the excel sheet.
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
String data = (row.getCell(j).getStringCellValue()+ "");
excelData[j][i] = data;
}
}
This transpose data when storing it into the array (note: excelData[j][i] and not excelData[i][j]).
With this, you can get all the contents of the first column as excelData[0].
I am using Java and POI to print some data to excel files. I think I am just missing a small logic to solve this question. I have data stored in array lists in following format:
a = [1,2,3] // arraylist
b = [4,5,6] // arraylist
c = [7,8,9] // arraylist
I want to print this data columnwise to excel file in below given format:
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9
The code that I am using is as below:
public final_out = new FileOutputStream(new File(final_output_path));
public XSSFWorkbook workbook = new XSSFWorkbook();
public XSSFSheet sheet = workbook.createSheet("data_vertical_final");
public Row row;
for (int i=0; i < a.size(); i++) {
String value = a.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(13);
cell.setCellValue(value);
}
for (int i=0; i < b.size(); i++) {
String value = b.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(15);
cell.setCellValue(value);
}
for (int i=0; i < c.size(); i++) {
String value = a.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(17);
cell.setCellValue(value);
}
workbook.write(final_out);
workbook.close();
final_out.close();
Error I am getting:
There is no error, but everything is getting overwritten in new excel file and the final output looks broken. Do I need to make new workbooks for every loop? or there is something I am missing.
P.S:
The data that is shown below is just an example. Some of my original files that I am using are between 1000 to 2000 values or maybe more.
I want to dynamically create the rows and extract the values from arraylists and store it in rows that I created.
Create only a.size() rows,
not a.size() squared rows.
Don't overwrite them in your code.
I assume that a.size() == b.size() and b.size() == c.size().
public List<Row> rows = new ArrayList<Row>(a.size());
for (int i=0; i < a.size(); i++) {
rows.add(sheet.createRow(i));
}
for (int i=0; i < a.size(); i++) {
String value = a.get(i);
Cell cell = rows.get(i).createCell(13);
cell.setCellValue(value);
}
for (int i=0; i < b.size(); i++) {
String value = b.get(i);
Cell cell = rows.get(i).createCell(15);
cell.setCellValue(value);
}
for (int i=0; i < c.size(); i++) {
String value = a.get(i);
Cell cell = rows.get(i).createCell(17);
cell.setCellValue(value);
}
If you already solve the problem:
It would be even cleaner to place a, b and c into one collection and use only one loop to iterate through them (in place of 3 separate loops).
I assume that a is the longest list.
Check this out:
public List<Row> rows = new ArrayList<>(a.size());
for (int i=0; i < a.size(); i++) {
rows.add(sheet.createRow(i));
}
List<List<String>> alphabet = new ArrayList<>();
alphabet.add(a);
alphabet.add(b);
alphabet.add(c);
for(int i=0; i < alphabet.size(); i++) {
for (int j=0; j < alphabet.get(i).size(); j++) {
String value = alphabet.get(i).get(j);
Cell cell = rows.get(j).createCell(13 + i*2); //<- 13, 15, 17...
cell.setCellValue(value);
}
}
//Using MySql Database. creating a search query for mobile phone from IMEI No. //in swing based desktop application
int coulmn_count=rsmd.getColumnCount();
DefaultTableModel dtm=new DefaultTableModel();
Vector column_name=new Vector();
Vector data_rows=new Vector();
for (int i = 1; i <=coulmn_count; i++) {
column_name.addElement(rsmd.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
JOptionPane.showMessageDialog(null,+coulmn_count);
while(rs.next())
{
for (int j = 0; j <coulmn_count; j++) {
data_rows=new Vector();
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
//JOptionPane.showMessageDialog(null,+coulmn_count);
table.setModel(dtm);
The ResultSet is 1 based, not 0 based:
It looks like you got the code correct for the heading names:
for (int i = 1; i <=coulmn_count; i++) {
column_name.addElement(rsmd.getColumnName(i));
}
But then you use 0 based for the column data.
for (int j = 0; j <coulmn_count; j++) {
data_rows=new Vector();
data_rows.addElement(rs.getString(j));
}
Fix the code to start the index from 1.
I am using JXL api. I want to fill an excel table that already have content, like:
123 321 12324
123 321 231
123 321 343
123 321 454
123 321 565
I am trying to write the next value after the fifth line, but I dont know how to do it. I only know how to create and write an excel table if it is empty. And I know how to read it. I was thinking that first I have to read it, and my array which would contain the values of the table would help me to pick the last value of the table then I would write the other values starting from there. I have these methods:
To read:
arquivo = new File("C:\\Users\\maniceto\\Desktop\\arq.xls");
planilha = Workbook.getWorkbook(arquivo);
Sheet[] abas = planilha.getSheets();
aba = planilha.getSheet(0);
matriz = new String[aba.getRows()][aba.getColumns()];
Cell[] cel;
for (int i = 0; i < matriz.length; i++) {
cel = aba.getRow(i);
for (int j = 0; j < matriz[0].length; j++) {
matriz[i][j] = cel[j].getContents();
}
}
System.out.println("Lines " + matriz.length);
System.out.println("Columns " + matriz[0].length);
System.out.println("");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[0].length; j++) {
System.out.print(matriz[i][j] + "\t");
}
System.out.println("");
}
To write an empty excel table:
WritableWorkbook workbookVazio = Workbook.createWorkbook(file);
WritableSheet sheet1 = workbookVazio.createSheet("First Sheet", 0);
TableModel model = table.getModel();
for (int i = 0; i < model.getColumnCount(); i++) {
Label column = new Label(i, 0, model.getColumnName(i));
sheet1.addCell(column);
}
int j = 0;
for (int i = 0; i < model.getRowCount(); i++) {
for (j = 0; j < model.getColumnCount(); j++) {
Label row = new Label(j, i + 1,
model.getValueAt(i, j).toString());
sheet1.addCell(row);
}
}
workbookVazio.write();
workbookVazio.close();
As stated by rgettman in this question, I would also advise to use Apache POI to handle Excel files with JAVA.
To append values using POI, you just need to get the current number of rows :
int rows = sheet.getPhysicalNumberOfRows();
POI is well documented and you will easily find several code examples on the net.
you could try something like
int lastRowNum = workbookVazio.getSheet("First Sheet").getLastRowNum();
int nextFreeRow = lastRowNum+1;
or you can use Apache POI theres a good tutorial here.