TXT

java excel

By Sara Diaz,2014-05-30 12:28
6 views 0
java excel

import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import java.awt.datatransfer.*; import java.util.*;

/**

    * ExcelAdapter 实现 JTables 中的复制粘贴

    * 剪贴板功能。 适配器所用的剪贴板数据格式

    * Excel 所用的剪贴板格式兼容。这提供了

    * 支持的 JTables Excel 间的互操作。

    */

    public abstract class ExcelAdapter implements ActionListener { protected String rowstring, value; protected Clipboard system; protected StringSelection stsel; protected JTable jTable1;

/**

    * Excel 适配器由 JTable 构成;

    * 它实现了 JTable 上的复制粘贴

    * 功能;并充当剪贴板监听程序。

    */

    public ExcelAdapter(JTable myJTable) { jTable1 = myJTable;

    KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK

    , false);

// 确定复制按键用户可以对其进行修改

    // 以实现其它按键组合的复制功能。

    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK

    , false);

// 确定粘贴按键用户可以对其进行修改

    // 以实现其它按键组合的复制功能。

    jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED

    );

    jTable1.registerKeyboardAction(this, "Paste", paste, JComponent.WHEN_FOCUSED

    );

    system = Toolkit.getDefaultToolkit().getSystemClipboard();

    }

/**

    * 此适配器运行图表的公共读方法。

    */

    public JTable getJTable() {

    return jTable1;

    }

    public void setJTable(JTable jTable1) { this.jTable1 = jTable1;

    }

    public abstract void copyAction();

    public abstract void pasteAction();

    public boolean checkSelection(){ // 检查以确保我们仅选择了单元格的相邻块

    int numcols = jTable1.getSelectedColumnCount();//选中行数

    int numrows = jTable1.getSelectedRowCount();//选中列数

    int[] rowsselected = jTable1.getSelectedRows();

    int[] colsselected = jTable1.getSelectedColumns();

    int last_row_idx = rowsselected[rowsselected.length - 1];//选中的最后一行

int first_row_idx = rowsselected[0];//选中的第一行

    int last_col_idx = colsselected[colsselected.length - 1];// 选中的最后一列

int first_col_idx = colsselected[0];//选中的第一列

    if (!((numrows - 1 == last_row_idx - first_row_idx && numrows == rowsselected

    .length)

    && (numcols - 1 == last_col_idx - first_col_idx && numcols == colsselected

    .length))){

    JOptionPane.showMessageDialog(null, "复制表格无效",

    "所选表格单元不连续",

    JOptionPane.ERROR_MESSAGE);

    return false;

    }

    else

    return true;

    }

/**

    * 在我们监听此实现的按键上激活这种方法。

    * 此处;它监听复制和粘贴 ActionCommands

* 包含不相邻单元格的选择导致选择无效;

    * 而且此后复制动作无法执行。

    * 粘贴的方法是将选定内容的左上角与

    * JTable 的当前选定内容的第一个元素对齐。

    */

    public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) {

    if(!checkSelection())

    return;

    this.copyAction();

    }

    if (e.getActionCommand().compareTo("Paste") == 0) {

    this.pasteAction();

    }

    }

    }

    这是个利用Ctrl + CCtrl + V来复制粘贴的方法;用这个类来处理你JTable上的热 键事件就可以了。

如何将jtable中的数据copy到其他文件上

    首先要明确的;其他文件不一定是java的文件;甚至与java一点也没有关系;比如操 作系统的记事本;微软的办公软件等等。

    实现的方法可以将jtable中的数据copy到系统的粘贴版上;然后通过粘贴板在copy 其他部分去。

    以下是具体实现的代码?

/:frame1.java

    import java.awt.*;

    import javax.swing.*;

    public class frame1 extends frame

     {

     borderlayout borderlayout1 = new borderlayout();

     jtable jtable1 ;

     object[][] data=new object[4][4];

     object header[]= {"jan","feb","mar","apr"};

    public static void main(string args[])

     {

     frame1 myframe=new frame1();

     myframe.setsize(new dimension(250,250));

     myframe.setvisible(true);

     }

public frame1()

     {

     super();

     try

     {

     jbinit();

     }

     catch (exception e)

     {

     e.printstacktrace();

     }

     }

private void jbinit() throws exception

     {

     for (int i=0;i<4;i++)

     for (int j=0;j<4;j++)

     data[i][j]=new integer(i*10+j);

     system.out.println("header length="+header[1]);

     jtable1=new jtable(data,header);

     jtable1.setcellselectionenabled(true);

     this.settitle("excel lent jtable");

     jtable1.setbackground(color.pink);

     this.setlayout(borderlayout1);

     this.setsize(new dimension(400, 300));

     this.setbackground(color.white);

     this.add(jtable1, borderlayout.center);

     / this is the line that does all the magic!

     exceladapter myad = new exceladapter(jtable1);

     }

    }

/:exceladapter.java

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import java.awt.datatransfer.*;

    import java.util.*;

    /**

    * exceladapter enables copy-paste clipboard functionality on jtables.

    * the clipboard data format used by the adapter is compatible with

    * the clipboard format used by excel. this provides for clipboard

    * interoperability between enabled jtables and excel. */

    public class exceladapter implements actionlistener

     {

     private string rowstring,value;

     private clipboard system;

     private stringselection stsel;

     private jtable jtable1 ;

     /**

     * the excel adapter is constructed with a

     * jtable on which it enables copy-paste and acts

     * as a clipboard listener.

     */

public exceladapter(jtable myjtable)

     {

     jtable1 = myjtable;

     keystroke copy = keystroke.getkeystroke(keyevent.vk_c,actionevent.ctrl_mask ,false);

     / identifying the copy keystroke user can modify this

     / to copy on some other key combination.

     keystroke paste = keystroke.getkeystroke(keyevent.vk_v,actionevent. ctrl_mask,false);

     / identifying the paste keystroke user can modify this

     /to copy on some other key combination.

    jtable1.registerkeyboardaction(this,"copy",copy,jcomponent.when_focused);

    jtable1.registerkeyboardaction(this,"paste",paste,jcomponent.when_focused );

     system = toolkit.getdefaulttoolkit().getsystemclipboard();

     }

     /**

     * public accessor methods for the table on which this adapter acts.

     */

    public jtable getjtable() {return jtable1;}

    public void setjtable(jtable jtable1) {this.jtable1=jtable1;}

     /**

     * this method is activated on the keystrokes we are listening to

     * in this implementation. here it listens for copy and paste actioncommands .

     * selections comprising non-adjacent cells result in invalid selection

     and

     * then copy action cannot be performed.

     * paste is done by aligning the upper left corner of the selection with

     the

     * 1st element in the current selection of the jtable.

     */

    public void actionperformed(actionevent e)

     {

     if (e.getactioncommand().compareto("copy")==0)

     {

     stringbuffer sbf=new stringbuffer();

     / check to ensure we have selected only a contiguous block of

     / cells

     int numcols=jtable1.getselectedcolumncount();

     int numrows=jtable1.getselectedrowcount();

     int[] rowsselected=jtable1.getselectedrows();

     int[] colsselected=jtable1.getselectedcolumns();

     if (!((numrows-1==rowsselected[rowsselected.length-1]-rowsselected [0] !!

     numrows==rowsselected.length) !!

    (numcols-1==colsselected[colsselected.length-1]-colsselected[0] !!

     numcols==colsselected.length)))

     {

     joptionpane.showmessagedialog(null, "invalid copy selection",

     "invalid copy selection",

     joptionpane.error_message);

     return;

     }

     for (int i=0;i

     {

     for (int j=0;j

     {

    sbf.append(jtable1.getvalueat(rowsselected[i],colsselected[j]));

     if (j

     }

     sbf.append("\n");

     }

     stsel = new stringselection(sbf.tostring());

     system = toolkit.getdefaulttoolkit().getsystemclipboard();

     system.setcontents(stsel,stsel);

     }

     if (e.getactioncommand().compareto("paste")==0)

     {

     system.out.println("trying to paste");

     int startrow=(jtable1.getselectedrows())[0];

     int startcol=(jtable1.getselectedcolumns())[0];

     try

     {

     string trstring= (string)(system.getcontents(this).gettransferdata (dataflavor.stringflavor));

     system.out.println("string is:"+trstring);

     stringtokenizer st1=new stringtokenizer(trstring,"\n");

     for(int i=0;st1.hasmoretokens();i++)

     {

     rowstring=st1.nexttoken();

     stringtokenizer st2=new stringtokenizer(rowstring,"\t");

     for(int j=0;st2.hasmoretokens();j++)

     {

     value=(string)st2.nexttoken();

     if (startrow+i< jtable1.getrowcount() !!

     startcol+j< jtable1.getcolumncount())

     jtable1.setvalueat(value,startrow+i,startcol+j);

     system.out.println("putting "+ value+"atrow="+startrow +i+"column="+startcol+j);

     }

     }

     }

     catch(exception ex){ex.printstacktrace();}

     }

     }

    }

Report this document

For any questions or suggestions please email
cust-service@docsford.com