How to export JFreeChart Data to csv file - java

I have used Java Swing along with JFreeChart for plotting graphs in the tool we are designing. Now i want to export the graph data to CSV file.(say upon right click on graph it should give an option of exporting to CSV and upon selecting it, a csv file should be created in some random location and save the graph data into it).
The important point here is how to save data into CSV from graph. I need to use Java Swing and JFreeChart for achieving this.

Try using this:
JFreeChart chart;
// ... initialization of chart
XYDataSet dataSet = chart.getXYPlot().getDataset();
Then use of the dataSet is pretty straightforward.

Here is a concrete example:
private void storeDataSet(JFreeChart chart, String filename) {
java.util.List<String> csv = new ArrayList<>();
if (chart.getPlot() instanceof XYPlot) {
Dataset dataset = chart.getXYPlot().getDataset();
XYDataset xyDataset = (XYDataset) dataset;
int seriesCount = xyDataset.getSeriesCount();
for (int i = 0; i < seriesCount; i++) {
int itemCount = xyDataset.getItemCount(i);
for (int j = 0; j < itemCount; j++) {
Comparable key = xyDataset.getSeriesKey(i);
Number x = xyDataset.getX(i, j);
Number y = xyDataset.getY(i, j);
csv.add(String.format("%s, %s, %s", key, x, y));
}
}
} else if (chart.getPlot() instanceof CategoryPlot) {
Dataset dataset = chart.getCategoryPlot().getDataset();
CategoryDataset categoryDataset = (CategoryDataset) dataset;
int columnCount = categoryDataset.getColumnCount();
int rowCount = categoryDataset.getRowCount();
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
Comparable key = categoryDataset.getRowKey(i);
Number n = categoryDataset.getValue(i, j);
csv.add(String.format("%s, %s", key, n));
}
}
} else {
throw new IllegalStateException("Unknown dataset");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename + ".csv"));) {
for (String line : csv) {
writer.append(line);
writer.newLine();
}
} catch (IOException e) {
throw new IllegalStateException("Cannot write dataset", e);
}
}

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;
}

How to append only one line/row for each iteration in appending values to CSV file in Java

I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.
CSV File:
Table:
Here's my source code in writing and reading the CSV:
public void writeCustomerCSV(){ // this creates a CSV file which stores the inputs of the user
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true, cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
if(itemTo2D[x][0] != null){
for(y = 0; y < itemTo2D[0].length; y++){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
}
catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file
String[][] twoDArray = new String[10][7];
int read2DStringIndex = 0;
int newVarIndexer = 0;
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
int ak = 0;
int sk = 0;
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
for(int c = 0; c < fromfile.length; c++){
if(fromfile[c].equals("-")){
sk = 0;
ak++;
if(c > 0){
if(!fromfile[c-1].equals("-")){
id = id + 1;
}
}
} else{
twoDArray[ak][sk] = fromfile[c];
sk++;
}
}
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
try{
if(cust[r][0].equals("null") == false){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
} catch(Exception e){
}
setrowcount++;
}
}
Is there something missing in my structure of the codes or is my logic in appending the values not right?
Your responses would indeed help me in resolving this issue.
Thank you very much.

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){
}

upload large .xlsx file in gui java

i have a large excel file containing 600.000 rows , i used XSSFWorkbook to upload the excel file at a Jtable in my GUI but it takes about 15 minutes to be done in eclipse and once i export my project to a jar file i can't do it even in the 15 minutes . Any help please ?
Here is the method , that i found in internet to upload my excel file .
void fillData(File file) {
int index = -1;
XSSFWorkbook workbook = null;
try {
try {
String f = file.getPath();
File file1 = new File(f);
OPCPackage opcPackage = OPCPackage.open(file1);
workbook = new XSSFWorkbook(opcPackage);
} catch (IOException ex) {
Logger.getLogger(ProjectApp3.class.getName()).log(Level.SEVERE, null, ex);
}
String[] strs = new String[workbook.getNumberOfSheets()];
//get all sheet names from selected workbook
for (int i = 0; i < strs.length; i++) {
strs[i] = workbook.getSheetName(i);
}
JFrame frame = new JFrame("Input Dialog");
//select sheet
String selectedsheet = (String) JOptionPane.showInputDialog(
frame, "Which worksheet you want to import ?", "Select Worksheet",
JOptionPane.QUESTION_MESSAGE, null, strs, strs[0]);
if (selectedsheet != null) {
for (int i = 0; i < strs.length; i++) {
if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
index = i;
}
XSSFSheet sheet = workbook.getSheetAt(index);
XSSFRow row = sheet.getRow(0);
//import headers data
headers.clear();
for (int i = 0; i < row.getLastCellNum(); i++) {
XSSFCell cell1 = row.getCell(i);
headers.add(cell1.toString());
}
//import data
data1.clear();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
Vector d = new Vector();
row = sheet.getRow(j);
int noofrows = row.getLastCellNum();
for (int i = 0; i < noofrows; i++) { //To handle empty excel cells
XSSFCell cell = row.getCell(i,
org.apache.poi.ss.usermodel.Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
d.add(cell.toString());
}
d.add("\n");
data1.add(d);
}
} else {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think the basic problem is that you're trying to give. your Jtable all the data at startup. This is going to be deeply problematic. You may want to write a custom subclass from AbstractTableModel. See the docs for Jtable that includes this:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
You can implement those three methods based on the info that POI gives you. But do lazy loading of the data, most especially for getValueAt(). Keep the spreadsheet file open and grab the data only when the user scrolls to view it.

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