Just starting to learn about JTable and I have a JButton that saves the contents of a JTable into a text file vertically. How can I write back the text file into the JTable?
The table has 4 columns (ex. ItemName | Description | Category | Date added). When each row is saved into the text file, it's saved vertically like a list.
I've tried saving the contents horizontally however this becomes a problem when the specific cell contains more than one word. (ex. saving "SD Card" from ItemName becomes "SD" in ItemName and "Card" in Description after reading the textfile basically shifting everything to the right)
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < table.getRowCount(); i++){//rows
for(int j = 0; j < table.getColumnCount(); j++){//columns
bw.write(table.getValueAt(i, j).toString()+"\n");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(AddItem.class.getName(), null).log(Level.SEVERE, null, ex);
}t(i, j).toString()+"\n");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(AddItem.class.getName(), null).log(Level.SEVERE, null, ex);
}
The code i've tried using is this however it isnt working.
for(int i = 0; i < lines.length; i++){
row = lines[i].toString().split(" ");
for(int j = 0; j < (row.length/4); j=j+4) {
model.addRow(new Object [] {row [j], row[j+1], row [j+2], row [j+3]});
}
}
Related
I managed to set label for my Excel, but I want to set values to cells which is an array and I want to set values with For loop but with this code my for loop doesn't work and label 4 and 5 don't write in my Excel file.
how can i set values to cells that those values change in every iteration?
String sdCard = getExternalFilesDir("/").getAbsolutePath();
File directory = new File(sdCard + "/MyFolder/");
//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
//Toast.makeText(getApplicationContext(),"dir",Toast.LENGTH_LONG).show();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
//wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
int a = 1;
workbook = Workbook.createWorkbook(file, wbSettings);
//Toast.makeText(getApplicationContext(),"done4",Toast.LENGTH_LONG).show();
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("Mydata1", 0);
//Toast.makeText(getApplicationContext(),"done3",Toast.LENGTH_LONG).show();
Label label0 = new Label(0,0,"Date");
Label label1 = new Label(1,0,"time");
Label label2 = new Label(2,0,"xCor");
Label label3 = new Label(3,0,"score");
Label label7 = new Label(2,1,xCor[2]);
try {
sheet.addCell(label0);
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
for(int i3 = 1; i3==j+1 ; i3++) {
String text = xCor[i3];
sheet.getWritableCell(text);
Label label4 = new Label(2,i3,text);
Label label5 = new Label(1,i3,text);
sheet.addCell(label4);
sheet.addCell(label5);
}
sheet.addCell(label7);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
It is difficult to tell ...because variable a is unused, j and xCor are being defined nowhere.
But one cannot have i3 == j+1 as the run condition for a for loop, because the condition will never be true and therefore the execution will never enter that control flow statement (dead code).
Most commonly, one may want to compare the loop index with the smaller or equal operator:
for (int i=1; i <= j; i++) { ... }
Logging to console can greatly help to determine what a loop actually does, for example:
Log.d(LOG_TAG, "i3 = " + i3 );
Also see the JavaDocs ...assuming that this is jxl.write.
Alike this you might eventually learn how it works.
I am trying to write a 2D Array to a text file but in a way that shows the row number at the beginning of each line as well as having a word before each value that is printed to the file. For example I would like the program to write each element like this ItemNo followed by the value that is contained in the array element. Like below:
Row 1: ItemNo3 ItemNo5 ItemNo8
Row 2: ItemNo9 ItemNo10 ItemNo12
Row 3: ItemNo15 ItemNo17 ItemNo18
I've been staring at my screen for awhile now and just cant get my head around this. Any help would be appreciated!
Try this code:
int[][] arr = new int[3][3];
//fill array
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[0].length; j++) {
arr[i][j] = j;
}
}
//create path
Path path = Paths.get("your\\path\\to\\file");
try {
//check if file exists; if not, create it
if(!(new File(path.toString()).exists())) {
Files.write(path, ("").getBytes());
}
int row = 1;
//iterate through the 2D array
for(int[] a : arr) {
//write the row number
Files.write(path, ("Row" + row + ": ").getBytes(), StandardOpenOption.APPEND);
for(int val : a) {
//write the ItemNo
Files.write(path, ("ItemNo" + val + " ").getBytes(), StandardOpenOption.APPEND);
}
row++;
//write a newline
Files.write(path, (System.getProperty("line.separator")).getBytes(), StandardOpenOption.APPEND);
}
} catch (Exception e) {
e.printStackTrace();
}
I have default table model fetch with data from database and i want to print in doc word as a table. How to achieve that. See the code below:
try {
try {
con = connCC.getDBconnection();
} catch (ClassNotFoundException ex) {
Logger.getLogger(CustomerSR.class.getName()).log(Level.SEVERE, null, ex);
}
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select * From Appointment");
while (rs.next()) {
for (int col = 0; col < 1; col++) {
rowData.add(rs.getString(1));
rowData.add(rs.getString(2));
rowData.add(rs.getString(3));
rowData.add(rs.getString(4));
rowData.add(rs.getString(5));
}
model.addRow(rowData);
}
window.display(model);
//window.display(names, phones, addresses);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
In the above comments, I see that you are already using Apache POI. If I understand correctly, you want to input data from a database into a table on a word document. Take a look at this tutorial on creating tables in word with Apache POI:
http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_tables.htm
You can set the text directly with the data that you retrieve from the database. I can post an example if you need it, but the tutorial does a pretty good job of showing what you need to do.
----UPDATE----
Sorry that it took me a while, went to lunch with the wife. Try this:
// Blank Document
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
// Create table
XWPFTable table = document.createTable();
// Table row
XWPFTableRow tableRow;
int rowCount = model.getRowCount() - 1;
int colCount = model.getColumnCount() - 1;
// Iterate through rows
for (int row = 0; row <= rowCount; row++) {
tableRow = table.getRow(row);
// Iterate through columns
for (int col = 0; col <= colCount; col++) {
tableRow.getCell(col).setText((String) model.getValueAt(row, col));
// If more columns, add cell
if (row == 0 && col < colCount) {
tableRow.addNewTableCell();
}
}
// If more rows, add row
if (row < rowCount) {
table.createRow();
}
}
// Write to word document and close file.
document.write(out);
out.close();
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();
}
}
}
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();
}