import java.io.File;
import java.io.IOException;
import java.util.Vector;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* 導出文件
* @author martin
*/
public class ExportFile {
/**
* 向Excel中導入數據
* @param vector 內容
* @param filepath 存儲路徑
* @param title 標題
*/
public void writeExcel(Vector<Vector<String>> vector, String filepath, String[] title) throws Exception{
File excel = new File(filepath);
WritableWorkbook workbook = Workbook.createWorkbook(excel);
WritableSheet sheet = workbook.createSheet("Sheet", 0);
Label label = null;
for(int i=0; i<title.length; i++) {
//Label(列號, 行號, 內容)
label = new Label(i, 0, title[i]); //put the title
sheet.addCell(label);
}
/*MD5 md5 = new MD5(); //使用MD5加密 */
for(int i=0; i<vector.size(); i++){
Vector<String> vtemp = vector.get(i);
for(int j=0; j<vtemp.size(); j++) {
String content = vtemp.get(j);
/*if(j == 1){
content = md5.toDigest(content);
}*/
label = new Label(j, i+1, content);
sheet.addCell(label);
}
}
workbook.write();
workbook.close();
}
————————————————下面爲調用部分(Start)—————————————————
/**
* 執行導出
* @param evt
*/
private void btnSaveActionPerformed(ActionEvent evt) {
TableModel model = (TableModel)tabDetail.getModel();
if(model.getValueAt(0, 0) != null) {
JFileChooser fileChooser = new JFileChooser(); //實例化一個文件選擇器
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); //只能選擇文件
fileChooser.showOpenDialog(this);
try{
if(fileChooser.getSelectedFile() != null){ //獲取選擇的文件
String strPath = fileChooser.getSelectedFile().getAbsolutePath();
if(!strPath.endsWith(".xls"))
strPath += ".xls";
writeExcel(model.getDataVector(), strPath, (String[])getColumuNames().toArray(new String[0]));
JOptionPane.showMessageDialog(null, "成功!", "溫馨提示", JOptionPane.INFORMATION_MESSAGE);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, " 失敗!", "溫馨提示", JOptionPane.INFORMATION_MESSAGE);
}
}
}
—————————————————上面爲調用部分(End)—————————————————
}