最近做项目需要做Excel表格的导出,最后选择了POI进行文件的导出
public class ExcelAction { // 这个输入流对应上面struts.xml中配置的那个excelStream,两者必须一致 private InputStream excelStream; private String fileName; //文件名 private File excelFile; private List<Salary> salary; public String test(){ //创建work对象 HSSFWorkbook work = new HSSFWorkbook(); //创建sheet对象 HSSFSheet sheet = work.createSheet("工资条"); //在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个 HSSFRow row1=sheet.createRow(0); //创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个 HSSFCell cell=row1.createCell(0); //设置单元格内容 cell.setCellValue("员工工资条"); //合并单元格(CellRangeAddress 参数依次为起始行,结束行,其实列,截止列) sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); HSSFRow row2=sheet.createRow(1); //创建单元格并设置单元格内容 row2.createCell(0).setCellValue("姓名"); row2.createCell(1).setCellValue("工号"); row2.createCell(2).setCellValue("本月工资"); row2.createCell(3).setCellValue("纳税"); //在sheet里创建第三行 HSSFRow row3=sheet.createRow(2); row3.createCell(0).setCellValue("李明"); row3.createCell(1).setCellValue("As178"); row3.createCell(2).setCellValue(3000.00); row3.createCell(3).setCellValue(20.00); //在sheet里创建第四行 HSSFRow row4=sheet.createRow(3); row4.createCell(0).setCellValue("张三"); row4.createCell(1).setCellValue("As177"); row4.createCell(2).setCellValue(5000.00); row4.createCell(3).setCellValue(30.00); //输出Excel表格 try { this.fileName = new String("工资条".getBytes(),"iso-8859-1"); // 设置文件名 ByteArrayOutputStream baos = new ByteArrayOutputStream(); work.write(baos); baos.flush(); byte[] aa = baos.toByteArray(); excelStream = new ByteArrayInputStream(aa, 0, aa.length); baos.close(); System.out.println("导出成功"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "success"; }
在strus.xml中进行以下配置
<result name="success" type="stream">
<paramname="contentType">application/vnd.ms-excel;charset=UTF-8"</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">attachment;filename="${fileName}.xls"</param> <!--这里的fileName必须与action中的成员变量名一致 -->
<param name="bufferSize">1024</param>
在配置文件中加入进行响应头文件名的配置就可以在导出时选择路径