Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » JFace » Export TableViewer data to a file(Export TableViewer data to a file)
Export TableViewer data to a file [message #1146328] Sun, 20 October 2013 04:39 Go to next message
Ken Brophy is currently offline Ken BrophyFriend
Messages: 9
Registered: May 2013
Location: Pittsfield, Massachusetts
Junior Member
Hi all,

I'm trying to iterate through the data in my TableViewer in order to write it to a CSV file (code below). The problem is that some of my TableViewerColumns use a StyledCellLabelProvider. Those columns don't return any text from their TableItems. I know I must be missing something simple but am just not seeing it. Thanks in advance for the help.

-Ken



final int[] columnOrder = table.getColumnOrder();
String[] line = new String[columnOrder.length];
for(int columnOrderIndex = 0; columnOrderIndex < columnOrder.length; 
        columnOrderIndex++) {
    int columnIndex = columnOrder[columnOrderIndex];
    TableColumn tableColumn = table.getColumn(columnIndex);
    
    line[columnOrderIndex] = tableColumn.getText();
}
csvWriter.writeNext(line);

final int itemCount = table.getItemCount();
for(int itemIndex = 0; itemIndex < itemCount; itemIndex++) {
    TableItem item = table.getItem(itemIndex);
    
    for(int columnOrderIndex = 0; 
            columnOrderIndex < columnOrder.length; 
            columnOrderIndex++) {
        int columnIndex = columnOrder[columnOrderIndex];
        line[columnOrderIndex] = item.getText(columnIndex);
    }
    csvWriter.writeNext(line);
}

Re: Export TableViewer data to a file [message #1147233 is a reply to message #1146328] Sun, 20 October 2013 18:56 Go to previous messageGo to next message
Ken Brophy is currently offline Ken BrophyFriend
Messages: 9
Registered: May 2013
Location: Pittsfield, Massachusetts
Junior Member
I've also tried having my StyledCellLabelProvider implement ILabelProvider...with no luck.
Re: Export TableViewer data to a file [message #1147399 is a reply to message #1147233] Sun, 20 October 2013 21:38 Go to previous messageGo to next message
Thorsten Schlathölter is currently offline Thorsten SchlathölterFriend
Messages: 312
Registered: February 2012
Location: Düsseldorf
Senior Member
Hi Ken,
I'd say the code is correct. If your table displays data, the items should provide the text via item.getText(columnIndex). I have just put your code into one of my examples and it works as it is.
Note that the labelProvider you use is just an implementational issue of the JFaceViewer. The TableViewer is used to decouple the data model from the table control itself. For example it relieves you from the burden to create the individual items and fill them with text all by yourself. The result of the TableViewer doing it's work is the table (GUI) properly filled with data.

Maybe you post a little bit more of your code. I'd say the problem is elsewhere.

HTH
Thorsten
Re: Export TableViewer data to a file [message #1148841 is a reply to message #1147399] Mon, 21 October 2013 19:37 Go to previous messageGo to next message
Ken Brophy is currently offline Ken BrophyFriend
Messages: 9
Registered: May 2013
Location: Pittsfield, Massachusetts
Junior Member
Thorsten,

Thank you for you time considering this issue! I've posted a complete reproducer below. I probably should have just taken the time to do this the first time. Smile The file created contains none of the text from the table. Sad

Thanks,
Ken

package forumexamples;
/*******************************************************************************
 * Copyright (c) 2006 Tom Schindl and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tom Schindl - initial API and implementation
 *******************************************************************************/

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

/**
 * A simple TableViewer to demonstrate usage
 * 
 * @author Tom Schindl <tom.schindl@bestsolution.at>
 *
 */
public class Snippet001TableViewer {
    private class MyContentProvider implements IStructuredContentProvider {

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
         */
        public Object[] getElements(Object inputElement) {
            return (MyModel[])inputElement;
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IContentProvider#dispose()
         */
        public void dispose() {
            
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
         */
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            
        }
        
    }
    
    public class MyModel {
        public int counter;
        
        public MyModel(int counter) {
            this.counter = counter;
        }
        
        public String toString() {
            return "Item " + this.counter;
        }
    }
    
    public Snippet001TableViewer(Shell shell) {
        final TableViewer v = new TableViewer(shell);
        
        TableViewerColumn column = new TableViewerColumn(v, SWT.LEFT);
        column.getColumn().setText("Name");
        column.getColumn().setResizable(true);
        column.getColumn().setWidth(150);
        column.setLabelProvider(new HyperlinkLabelProvider(v.getTable(), 
                new LabelProvider()));
        
        v.setContentProvider(new MyContentProvider());
        
        MyModel[] model = createModel();
        v.setInput(model);
        v.getTable().setHeaderVisible(true);
        v.getTable().setLinesVisible(true);
        
        shell.getDisplay().asyncExec(new Runnable() {
            public void run() {
                exportTable(v);
            }
        });
    }
    
    private MyModel[] createModel() {
        MyModel[] elements = new MyModel[10];
        
        for( int i = 0; i < 10; i++ ) {
            elements[i] = new MyModel(i);
        }
        
        return elements;
    }
    
    private class HyperlinkLabelProvider extends StyledCellLabelProvider 
        implements ILabelProvider {

        private final Color linkColor;
        private final LabelProvider labelProvider;
        
        public HyperlinkLabelProvider(Composite parent, 
                LabelProvider labelProvider) {
            this.labelProvider = labelProvider;
            
            linkColor = new Color(parent.getDisplay(), 0, 0, 255);
        }
        
        @Override
        public void dispose() {
            super.dispose();
            if (linkColor != null) {
                linkColor.dispose();
            }
        }
        
        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.StyledCellLabelProvider#paint(org.eclipse.swt.widgets.Event, java.lang.Object)
         */
        @Override
        protected void paint(Event event, Object element) {
            GC gc = event.gc;
            
            // remember colors to restore the GC later
            Color oldFg = gc.getForeground();
            
            gc.setForeground(linkColor);
            gc.drawText(getText(element), event.x, event.y);
            
            gc.setForeground(oldFg);
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
         */
        @Override
        public Image getImage(Object element) {
            return labelProvider.getImage(element);
        }

        /* (non-Javadoc)
         * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
         */
        @Override
        public String getText(Object element) {
            return labelProvider.getText(element);
        }
    }
    
    public void exportTable(TableViewer tableViewer) {
        // TODO: add logic to ask user for the file location
        File file = new File("exportedTable.txt");
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            
            final Table table = tableViewer.getTable();
            final int[] columnOrder = table.getColumnOrder();
            for(int columnOrderIndex = 0; columnOrderIndex < columnOrder.length; 
                    columnOrderIndex++) {
                int columnIndex = columnOrder[columnOrderIndex];
                TableColumn tableColumn = table.getColumn(columnIndex);
                
                writer.write(tableColumn.getText());
                writer.write(",");
            }
            writer.write("\n");
            
            final int itemCount = table.getItemCount();
            for(int itemIndex = 0; itemIndex < itemCount; itemIndex++) {
                TableItem item = table.getItem(itemIndex);
                
                for(int columnOrderIndex = 0; 
                        columnOrderIndex < columnOrder.length; 
                        columnOrderIndex++) {
                    int columnIndex = columnOrder[columnOrderIndex];
                    writer.write(item.getText(columnIndex));
                    writer.write(",");
                }
                writer.write("\n");
            }
            
        } catch(IOException ioe) {
            // TODO: add logic to inform the user of the problem
            System.err.println("trouble exporting table data to file");
            ioe.printStackTrace();
        }
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        Display display = new Display ();
        Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());
        new Snippet001TableViewer(shell);
        shell.open ();
        
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        
        display.dispose ();
    }
}
Re: Export TableViewer data to a file [message #1149713 is a reply to message #1148841] Tue, 22 October 2013 08:54 Go to previous messageGo to next message
Thorsten Schlathölter is currently offline Thorsten SchlathölterFriend
Messages: 312
Registered: February 2012
Location: Düsseldorf
Senior Member
Hi Ken,
I am sorry for giving wrong advice. Contrary to my assumption the table item must not be properly configured when it displays the data. And also the labelprovider plays an important role in your case, since it actually does the painting of the table cell. So the problem in your case is really the custom label provider which you provide.

Please look at StyledCellLabelProvider.update(). It says there

public void update(ViewerCell cell) {
   // clients must override and configure the cell and call super
   super.update(cell); // calls 'repaint' to trigger the paint listener
}


Since you did not override this method to set the cell text and image, it is not there when you are trying to export. Please look at

org.eclipse.jface.viewers.ColumnLabelProvider


for a default implementation of that method.

In the end, the solution to your problem is to add the following method to your HyperlingLabelProvider:


public void update(ViewerCell cell) {
   super.update(cell); 
   Object element = cell.getElement();
   cell.setText(getText(element));
   Image image = getImage(element);
   cell.setImage(image);
} 


Note: Instead of using StyledCellLabelProvider you could also use an ITableColorProvider.

public class MyLabelProvider extends LabelProvider implements
		ITableLabelProvider, ITableColorProvider {

	@Override
	public Color getForeground(Object element, int columnIndex) {
		return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
	}

	@Override
	public Color getBackground(Object element, int columnIndex) {
		return null;
	}

	@Override
	public Image getColumnImage(Object element, int columnIndex) {
		return super.getImage(element);
	}

	@Override
	public String getColumnText(Object element, int columnIndex) {
		return super.getText(element);
	}
}


public Snippet001TableViewer(Shell shell) {

	final TableViewer v = new TableViewer(shell, SWT.MULTI | SWT.H_SCROLL
			| SWT.V_SCROLL | SWT.BORDER);
	TableColumn tc = new TableColumn(v.getTable(), SWT.NONE);
	tc.setWidth(100);
	tc.setText("Name");

	v.setLabelProvider(new MyLabelProvider());

	v.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
	v.setContentProvider(new MyContentProvider());

	MyModel[] model = createModel();
	v.setInput(model);
	v.getTable().setHeaderVisible(true);
	v.getTable().setLinesVisible(true);

	shell.getDisplay().asyncExec(new Runnable() {
		public void run() {
			exportTable(v);
		}
	});
}



HTH
Thorsten
Re: Export TableViewer data to a file [message #1150473 is a reply to message #1149713] Tue, 22 October 2013 20:07 Go to previous messageGo to next message
Ken Brophy is currently offline Ken BrophyFriend
Messages: 9
Registered: May 2013
Location: Pittsfield, Massachusetts
Junior Member
Thorsten, ahhhh, most excellent advice! It's working great now!
Thank you so much for the help, I'm quite new to the JFace world and am still figuring things out (as you can tell).

Note that I would have used the simpler ITableColorProvider but I also underline the hyperlinks in the cells. I just didn't want to add further complication to the reproducer as well as require extra bundles. If there's an easier way to do that as well, I'd love to hear about it! Smile
Re: Export TableViewer data to a file [message #1150538 is a reply to message #1150473] Tue, 22 October 2013 21:09 Go to previous message
Thorsten Schlathölter is currently offline Thorsten SchlathölterFriend
Messages: 312
Registered: February 2012
Location: Düsseldorf
Senior Member
It's OK to use the StyledCellLabelProvider. I just wanted to point out a simpler solution to what was implemented in the example (currently no underlining there). If you are aiming for underlining the text you will have to draw the line by yourself. This can be done by adding a paint listener (SWT.PaintItem, SWT.EraseItem, SWT.MeasureItem) yourself or by using the StyledCellLabelProvider and let that labelprovider register the respective listeners.

Regards,
Thorsten
Previous Topic:Observing map doesn't update the UI
Next Topic:NPE at editor opening from toolbar
Goto Forum:
  


Current Time: Thu Mar 28 09:27:48 GMT 2024

Powered by FUDForum. Page generated in 0.02296 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top