Escape comma when using csv writer - java

My application writes the data from Jtable to a csv file.
I use the below function:
public static boolean exportToCSV(JTable RnRFetchTable,String pathToExportTo) {
try {
DateFormat writeDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date writeDate = new Date();
TableModel model = RnRFetchTable2.getModel();
FileWriter csv = new FileWriter(new File("C:/Users/Desktop/TableExport" + writeDateFormat.format(writeDate) + ".csv"));
for (int i = 0; i < model1.getColumnCount(); i++) {
csv.write(model1.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model1.getRowCount(); i++) {
for (int j = 0; j < model1.getColumnCount(); j++) {
csv.write(model1.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
JOptionPane.showMessageDialog(null,"Export Successful!");
return true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"Error! Excel cannot be exported!");
}
return false;
}
This code works fine when one of the columns don't have the comma, but when it does, the delimiting happens wherever the "," comes. How to write the csv by escaping comma?

You can surround your text with double quotes:
csv.write("\"" + model1.getValueAt(i, j).toString() + "\",");

Related

How to save from JTable to CSV or Excel?

Is there a way to save JTable data to excel? I would like to save the data that I input from the program, from the table and then to a CSV file.
I would like to have it so that there is a button that will then save the inputted data from the GUI into the table and then to the CSV file.
This may help you:-
Method to write to a csv file.
public static void exportToCSV(JTable table,
String path) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File(path));
for (int i = 0; i < model.getColumnCount(); i++) {
csv.write(model.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
csv.write(model.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
} catch (IOException e) {
System.out.println("Error "+e);
}
}
For reading and showing it to a JTable you can use OpenCSV.
CSVReader reader = new CSVReader(new FileReader("file.csv"));
List list = reader.readAll();
JTable table = new JTable(list.toArray());
There is no 'magic function' of a JTable that I know of that will do this. JTable is a UI component, and what you're asking for is a data function, not a user interface function. And it doesn't have much to do with eclipse, which is just the IDE one uses to write the code.
I think what you may be looking for is the model on which the JTable is based. The first solution that occurs to me is to alter that model code to have a method that will write out the data in the format you want; then a(nother) button on your UI would invoke this method on the model to write out the data when the user chooses. There are likely other ways you might get this done, but that seems the most straightforward and easiest.
You can try this code:
public static boolean convertToCSV(JTable table,
String path) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File(path));
for (int i = 0; i < model.getColumnCount(); i++) {
csv.write(model.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
csv.write(model.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

Importing a .csv file data into java table showing incomplete information

I'm trying to import a .csv file to display in my Java Table. But it shows incomplete data after reaching a certain point.
When I change the data to previous ones it displays just fine
My csv file looks fine too..
Finally this is how I read the file into the table from a menu item in my interface
File file = new File("C:\\Users\\User\\Desktop\\Emerging Coursework\\12_book_list_csv.csv");
try{
Scanner inputStream = new Scanner(file);
inputStream.nextLine();
while (inputStream.hasNextLine()) {
String data = inputStream.nextLine();
String[] values = data.split(",");
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
int rowCount = browseTable.getRowCount();
System.out.println("rowCount: " + rowCount);
int columnCount = browseTable.getColumnCount();
System.out.println("columnCount: " + columnCount);
int nextRow = 0;
boolean emptyRowFlag = false;
String testValue;
do {
testValue = (String) browseTable.getValueAt(nextRow, 0);
if (testValue != null && testValue.length()!=0) {
System.out.println("testvalue:" + testValue);
System.out.println("testValue.length" + testValue.length());
nextRow++;
} else{
emptyRowFlag = true;
}
} while(nextRow < rowCount && !emptyRowFlag);
for (int i = 0; i < columnCount; i++){
browseTable.setValueAt(values[i], nextRow, i);
}
}
} catch(Exception e){
}

How to dynamically rename csv exports, when using csv writer in Java

I have the below code which exports a Jtable as Excel csv export.
I tried appending the file (boolean true), but the append happens within the same file itself.
public static boolean exportToCSV(JTable table,String pathToExportTo) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File("C:/Users/user/Desktop/test.csv"));
for (int i = 0; i < model.getColumnCount(); i++) {
csv.write(model.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
csv.write(model.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
JOptionPane.showMessageDialog(null,"Export Successful!");
return true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"Error! Excel cannot be exported!");
}
return false;
This is working fine, but this overwrites the existing file. I would want this to be exported as a different file and probably rename as text(1).csv
You could use a method to compute report output file:
File resolveFileName(){
String directory ="C:/Users/user/Desktop/";
File res = new File(directory + "test.csv");
if(!res.exists()){
return res;
}
int filesInDirectoryCount = (new File(directory)).listFiles().length;
String fileName = "test_"+filesInDirectoryCount+".csv";
return new File(directory+fileName);
}
Usage:
FileWriter csv = new FileWriter(resolveFileName);
This will add a numer to the file name, based on numer of files in this directory. So it should help with this problem.

Writing to a text file using Java gets cut short

I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}
Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.
Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)
See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).

How to convert Excel to XML using java?

i want to convert my input Excel file into the Output XML file.
If anybody has any solution in java for how to take input Excel file and how to write to XML as output,please give any code or any URL or any other solution.
Thanks,
Mishal Shah
Look into the jexcel or Apache POI libraries for reading in the Excel file.
Creating an XML file is simple, either just write the XML out to a file directly, or append to an XML Document and then write that out using the standard Java libs or Xerces or similar.
I have done conversion of Excel(xlsx) to xml in Java recently. I assumed each row in excel as a single object here. Here are the steps I followed:-
Read Excel file using Apache POI
Created a xsd file and
generated corresponding classes
Read each row created, created corresponding objects and initilaized values using the generated getter/setter methods in the classes
Added the objects to an arraylist which holds only objects the same type
Using Jaxb Marshelled the arraylist object to an output file
Ready to provide code if required
Here's where you can start https://sites.google.com/site/arjunwebworld/Home/programming/jaxb-example
JExcel was easy for me to use. Put jxl.jar on the classpath and code something like:
File excelFile = new File(excelFilename);
// Create model for excel file
if (excelFile.exists()) {
try {
Workbook workbook = Workbook.getWorkbook(excelFile);
Sheet sheet = workbook.getSheets()[0];
TableModel model = new DefaultTableModel(sheet.getRows(), sheet.getColumns());
for (int row = 0; row < sheet.getRows(); row++) {
for (int column = 0; column < sheet.getColumns(); column++) {
String content = sheet.getCell(column, row).getContents();
model.setValueAt(content, row, column);
}
}
previewTable.setModel(model);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: " + e);
}
} else {
JOptionPane.showMessageDialog(null, "File does not exist");
}
See http://jexcelapi.sourceforge.net/resources/faq/ to get started and link to download area.
File excelFile = new File(excelFilename);
// Create model for excel file
if (excelFile.exists()) {
try {
Workbook workbook = Workbook.getWorkbook(excelFile);
Sheet sheet = workbook.getSheets()[0];
TableModel model = new DefaultTableModel(sheet.getRows(), sheet.getColumns());
for (int row = 0; row < sheet.getRows(); row++) {
for (int column = 0; column < sheet.getColumns(); column++) {
String content = sheet.getCell(column, row).getContents();
model.setValueAt(content, row, column);
}
}
previewTable.setModel(model);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: " + e);
}
} else {
JOptionPane.showMessageDialog(null, "File does not exist");
}
Download jxl and use this code
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.swing.text.BadLocationException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Font;
import jxl.read.biff.BiffException;
public class XlsToXml {
public String toXml(File excelFile) throws IOException, BiffException {
try {
String xmlLine = "";
String rowText = "";
String colText = "";
String isBold = "";
Font font = null;
String cellCol = "";
String cellAddress = "";
Cell cell = null;
Workbook workbook = Workbook.getWorkbook(excelFile);
xmlLine += "<workbook>" + "\n";
for (int sheet = 0; sheet < workbook.getNumberOfSheets(); sheet++) {
Sheet s = workbook.getSheet(sheet);
xmlLine += " <sheets>" + "\n";
Cell[] row = null;
for (int i = 0; i < s.getRows(); i++) {
row = s.getRow(i);
for (int j = 0; j < row.length; j++) {
if (row[j].getType() != CellType.EMPTY) {
cell = row[j];
cellCol=columnName(cell.getColumn());
cellCol=" colLetter=\""+cellCol+"\"";
cellAddress=" address=\""+cellAddress(cell.getRow()+1,cell.getColumn())+"\"";
isBold = cell.getCellFormat().getFont().getBoldWeight() == 700 ? "true" : "false";
isBold = (isBold == "false" ? "" : " isBold=\"true\"");
colText += " <col number=\"" + (j + 1) + "\"" + isBold +cellAddress+ ">";
colText += "<![CDATA[" + cell.getContents() + "]]>";
colText += "</col>" + "\n";
rowText += cell.getContents();
}
}
if (rowText != "") {
xmlLine += " <row number=\"" + (i + 1) + "\">" + "\n";
xmlLine += colText;
xmlLine += " </row>" + "\n";
}
colText = "";
rowText = "";
}
xmlLine += " </sheet>" + "\n";;
}
xmlLine += "</workbook>";
return xmlLine;
} catch (UnsupportedEncodingException e) {
System.err.println(e.toString());
}
return null;
}
private String cellAddress(Integer rowNumber, Integer colNumber){
//return "$"+columnName(colNumber)+"$"+rowNumber;
return columnName(colNumber)+rowNumber;
}
private String columnName(Integer colNumber) {
Base columns = new Base(colNumber,26);
columns.transform();
return columns.getResult();
}
class Base {
String[] colNames = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");
String equalTo;
int position;
int number;
int base;
int[] digits;
int[] auxiliar;
public Base(int n, int b) {
position = 0;
equalTo = "";
base = b;
number = n;
digits = new int[1];
}
public void transform() {
if (number < base) {
digits[position] = number;
size();
} else {
digits[position] = number % base;
size();
position++;
number = number / base;
transform();
}
}
public String getResult() {
for (int j = digits.length - 2; j >= 0; j--) {
equalTo += colNames[j>0?digits[j]-1:digits[j]];
}
return equalTo;
}
private void size() {
auxiliar = digits;
digits = new int[auxiliar.length + 1];
System.arraycopy(auxiliar, 0, digits, 0, auxiliar.length);
}
}
}

Categories