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)—————————————————
}