用java程序導出數據到Excel文檔

1.問題產生
如何用java程序直接打開一個Excel文件
2.解決

//啓動帶有空格的文件

   String[] cmdarray=new String[]{"cmd.exe","/c","C://Documents and Settings//Administrator//桌面//results.xls"};
   Runtime.getRuntime().exec(cmdarray);

//啓動不帶空格的文件
   Runtime.getRuntime().exec("cmd  /c  start  d://a.xls")                                           
   getRuntime()是取得系統運行時環境 
   start參數表名直接啓動excel文件,相當於雙擊操作 ,是個windows命令.
-------------------------------------------------------------------------------------------------------------------------------

package com.sun.my;

 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.JTable;
import javax.swing.table.TableModel;

 

/**
 *
 * @author Administrator
 */
public class ExcelExporter {
        public void exportTable(JTable table, String path) throws IOException {
                TableModel model = table.getModel();
                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"gbk");
                for(int i=0; i < model.getColumnCount(); i++) {
                        out.write(model.getColumnName(i) + "/t");
                }
                out.write("/n");
                for(int i=0; i<model.getRowCount(); i++) {
                        for(int j=0; j < model.getColumnCount(); j++) {
                                out.write(model.getValueAt(i,j).toString()+"/t");
                        }
                        out.write("/n");
                }
                out.close();
                String[] cmdarray=new String[]{"cmd.exe","/c",path};
                Runtime.getRuntime().exec(cmdarray);
        }
}

------------------------------------------------------------------以下爲調用-------------------------------------------------------

private void diaoyong() {                                          
        String strPath = "C://Documents and Settings//Administrator//桌面//results.xls";
        try {
                if(model != null){
                        this.jTable1.setModel(model);
                        ExcelExporter exp = new ExcelExporter();
                        exp.exportTable(jTable1, strPath);
                }
        } catch (IOException ex) {
                Logger.getLogger(SearchUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章