java工具類導出jtable數據到excel工作表

jopen 8年前發布 | 28K 次閱讀 Java開發

package com.zhong.tools;

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;

import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.TableModel;

import jxl.Workbook; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException;

public class ExcelExporter {       public ExcelExporter() {       }       public void exportTable(JTable table, File file) throws IOException {           try {               OutputStream out = new FileOutputStream(file);               TableModel model = table.getModel();               WritableWorkbook wwb = Workbook.createWorkbook(out);               // 創建字表,并寫入數據               WritableSheet ws = wwb.createSheet("中文", 0);               // 添加標題               for (int i = 0; i < model.getColumnCount(); i++) {                   jxl.write.Label labelN = new jxl.write.Label(i, 0, model.getColumnName(i));                   try {                       ws.addCell(labelN);                   } catch (RowsExceededException e) {                       // TODO Auto-generated catch block                       e.printStackTrace();                   } catch (WriteException e) {                       // TODO Auto-generated catch block                       e.printStackTrace();                   }               }               // 添加列               for (int i = 0; i < model.getColumnCount(); i++) {                   for (int j = 1; j <= model.getRowCount(); j++) {                       jxl.write.Label labelN = new jxl.write.Label(i, j, model.getValueAt(j - 1, i).toString());                       try {                           ws.addCell(labelN);                       } catch (RowsExceededException e) {                           e.printStackTrace();                       } catch (WriteException e) {                           e.printStackTrace();                       }                   }               }               wwb.write();               try {                   wwb.close();               } catch (WriteException e) {                   e.printStackTrace();               }           } catch (FileNotFoundException e) {               JOptionPane.showMessageDialog(null, "導入數據前請關閉工作表");           }       }   }</pre>


來自: http://my.oschina.net/passer007/blog/552515

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!