/**
这个方法需要的包可以直接在根据我的ID搜资源,是poi的jar包
* 导出excel action方法
*/
private String saveExcelFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
/* 定义一个保存选择框 */
JFileChooser dialog = new JFileChooser();
/* 保存文件类型 */
javax.swing.filechooser.FileFilter filter = new FileNameExtensionFilter("Excel文件(*.xls)", ".xls");
/* 文件标题 */
dialog.setDialogTitle("导出Excel");
dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
dialog.setDialogType(JFileChooser.SAVE_DIALOG);
/* 保存框类别 */
dialog.setFileFilter(filter);
int result = dialog.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
/* 获取选择框属性 */
File file = dialog.getSelectedFile();
/* 得到文件全名 */
String filePath = file.getAbsolutePath()+".xls";
//获取数据库查询list格式的数据
List list =null;
//第一行数据
String[] title=new String[]{"序号","售票日期","班次","售票金额","票号"};
//调用导出方法
servant.exportExcel("导出Excel",title,list,filePath);
PrintWriter writer;
try {
writer = response.getWriter();
writer.print("导出成功!");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/**
* 导出excel数据通用方法
* @param title
标题
* @param headers
数据头(第一行数据)
* @param list
返回内容
* @param path
导出路径
*/
public void exportExcel(String title, String[] headers,
List list ,String path ) {
OutputStream out = null;
try {
out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 25);
// 产生表格第一行的标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
for(Integer i =0;i<list.size();i++){
// 从第二行开始创建内容行
row = sheet.createRow(i+1);
//
循环获取list数据
Object[] testmap = (Object[])list.get(i);
//
循环将数据保存进表格中
for(int j = 0;j < testmap.length; j++){
//
根据每行数据个数循环保存数据
HSSFCell cell = row.createCell(j);
//
保存类别
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
//保存值
HSSFRichTextString text = new HSSFRichTextString(testmap[j].toString());
//保存列值
cell.setCellValue(text);
}
}
try {
workbook.write(out);
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}