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();
}
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'm trying to modify an excel file but for some reason which I do not understand the method Cell.setCellValue does not work in my code.
What I'm actually doing is:
-I'm opening an excel file and saving the content that interests me in a HashMap. This works i can print the content of the hashmap.
-Then I'm trying to modify another excel file with the data saved in the HashMap but this does not happen for some reason.
Here is my code:
public File manipulateDocumentITM(File xlFile) {
// ADDING DATA FROM AN EXCEL FILE TO A HASHMAP
HashMap<Integer, ArrayList<Date>> hashMap = new HashMap<>();
try {
FileInputStream inFile = new FileInputStream(xlFile);
Workbook workbookInFile = new XSSFWorkbook(inFile);
Sheet sheetInFile = workbookInFile.getSheetAt(0);
Iterator<Row> rowIteratorInFile = sheetInFile.iterator();
int rowCountInFile = 5, key = 0, countEmpty = 0, rowCountModelFile = 10;
while (rowIteratorInFile.hasNext()) {
ArrayList<Date> arrayList = new ArrayList<>();
Row rowInFile = rowIteratorInFile.next();
if (rowInFile.getRowNum() == rowCountInFile) {
key++;
Iterator<Cell> cellIteratorInFile = rowInFile.cellIterator();
arrayList = new ArrayList<>();
while (cellIteratorInFile.hasNext()) {
Cell cell = cellIteratorInFile.next();
if ((cell.getCellType() == CellType.NUMERIC) && (cell.getColumnIndex() != 0)) {
Date data = cell.getDateCellValue();
arrayList.add(data);
}
}
hashMap.put(key, arrayList);
rowCountInFile = rowCountInFile + 4;
}
}
inFile.close();
// DATA SAVED IN HASHMAP ABOVE NEXT IM JUST PRINTING THE VALUES IN THE HASHMAP
for (Integer I : hashMap.keySet()) {
ArrayList<Date> replaceArray = hashMap.get(I);
System.out.println("***");
for (int i = 0; i < replaceArray.size(); i++) {
System.out.println(replaceArray.get(i).getHours());
}
}
// CODE THAT SUPPOSE TO MODIFY EXCEL FILE WITH THE DATA FROM THE HASHMAP
String modelPath = "/home/h1dr0/Documents/unimineral/Model foaie de prezenta (another copy).xlsx";
FileInputStream modelFile = new FileInputStream(modelPath);
Workbook workbookModel = new XSSFWorkbook(modelFile);
Sheet sheetModelFile = workbookModel.getSheetAt(0);
Iterator<Row> rowIteratorModelFile = sheetModelFile.iterator();
ArrayList<Date> replaceArray2 = new ArrayList<>();
Iterator it = hashMap.entrySet().iterator();
while (rowIteratorModelFile.hasNext()) {
Row rowModelFile = rowIteratorModelFile.next();
if (rowModelFile.getRowNum() == rowCountModelFile) {
Iterator<Cell> cellIteratorModelFile = rowModelFile.cellIterator();
Map.Entry pair = (Map.Entry)it.next();
replaceArray2 = (ArrayList<Date>) pair.getValue();
while (cellIteratorModelFile.hasNext()) {
Cell cell = cellIteratorModelFile.next();
if (replaceArray2.size() != 0) {
for (int i = 0; i < replaceArray2.size(); i++) {
if ((replaceArray2.get(i).getHours() != 0) && replaceArray2.get(i).toString() != "" && (cell.getColumnIndex() != 18)) {
// THIS DOES NOT WORK
cell.setCellValue(replaceArray2.get(i).getHours());
}
else {
cell.setCellValue(" ");
}
}
} else {
cell.setCellValue(" ");
}
}
rowCountModelFile = rowCountModelFile + 3;
}
}
modelFile.close();
//}
FileOutputStream outputStream = new FileOutputStream("/home/h1dr0/Documents/unimineral/generate.xlsx",false);
workbookModel.write(outputStream);
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return xlFile;
}
I also checked with debugger and the cell values are modified to what it suppose to...
cell.setCellValue(8);
if(cell.getCellType() == CellType.NUMERIC) {
System.out.println("cell: " + cell.getNumericCellValue());
}
prints 8
What i get is the same file .. no modification.
Please help , thank you !
Excel is designed to work on huge tables. Only the used ones are stored in memory or the document. That means before you can populate a cell, it first has to be created.
In your code I only see that you iterate over the existing cells but you do not try to create them. Maybe that is the issue?
I decided to try another approach in modifying excel files. I'm using UIPath for automation. It works good I managed to do this by using their excel activity dependencies in Studio ( their IDE let's say ).
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]});
}
}
I have created a table viewer and displaying the contents in the table.Now i have created a button called save which has to save all the contents of the table into a file .I have created a dialog window to give the file name but i am not getting how to save the complete data in the table to a text file.So how can we save the complete data in the table to text file .The code for dialogbox is as follows
Button btnSave= new Button(topComposite, SWT.BUTTON2);
btnSave.setText("Save");
//btnSave.addSelectionListener(new OpenFiler());
btnSave.addSelectionListener(new SelectionAdapter() {
#Override public void widgetSelected(final SelectionEvent e){
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setText("Save");
String[] filterExt = { "*.log" };
dialog.setFilterNames(filterExt);
String absolutePath = dialog.open();
if (absolutePath == null)
return;
dialog.setFilterExtensions(new String[] { "*.log" }); dialog.setFilterPath("c:\\"); // Windows path
}
});
Please help me how can we save the complete data in the table to a text file.
Use this code. viewer is the instance of your table viewer. Add this code at the end of the addSelectionListener method of button btnSave.
TableItem[] items = viewer.getTable().getItems();
File fl = new File(dialog.getFilterPath() + File.separator + dialog.getFileName());
FileWriter flwr;
int cls = viewer.getTable().getColumnCount();
try {
flwr = new FileWriter(fl);
for (int i = 0; i < items.length; i++) {
for (int j = 0; j <= cls; j++) {
flwr.write(items[i].getText(j) + "\t");
}
flwr.write("\n");
}
flwr.flush();
flwr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Hi I am trying to convert oracle jdbc resultset to csv file. Below is the code used. Issue occures when there is value like below in the field. It deforms the output csv and all this come in separate line rather than in one field.
Value in Field comes in csv as
[<333message:Runtime error in script' ProcessItem: ' Type: 'ITEM'" 1:0).Internal Script error: java.lang.NullPointerException
Script (line 1):
setHours = 0 ;
if(ts.instanceId == null)
" 3 : ts.instanceId = 0 ;"
Step >]
int ncols = result.getMetaData().getColumnCount();
System.out.println("ColumnCout"+ncols);
FileOutputStream fos=new FileOutputStream(new File("C:\\test.csv"),false);
Writer out = new OutputStreamWriter(new BufferedOutputStream(fos),"UTF_8");
for (int j=1; j<(ncols+1); j++) {
out.append(result.getMetaData().getColumnName (j));
if (j<ncols) out.append(","); else out.append("\r\n");
}
int m =1;
while (result.next()) {
for (int k=1; k<(ncols+1); k++) {
out.append(result.getString(k));
if (k<ncols) out.append(","); else out.append("\r\n");
}
//System.out.println("No of rows"+m);
m++;
}
Are you using "java.sql.ResultSet" class?
If yes, see the library in this link http://opencsv.sourceforge.net/
See an example:
CSVWriter csvWriter = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
java.sql.ResultSet myResultSet = .... ;
csvWriter.writeAll(myResultSet, includeHeaders);
Get the value for the column that could have new lines as
String multiLine = null;
if (k == <col_index> && (mutiLine = rs.getString(k)) != null)
out.append(multiLine.replaceAll("\\n", ""));
else
out.append(result.getString(k));
You could filter all the columns as well but then would incur some performance hit.