1.在index.xml编写代码
<a href="exportExcel">导出Excel</a><br>
2.在struts.xml配置
<struts>
<package name="team" extends="struts-default" namespace="/">
<!--导出Excel-->
<action name="exportExcel" class="com.iteye.action.TestAction"
method="excelExport">
<result type="stream">
<param name="contentType">application/vnd.ms-excel;charset=utf8</param>
<param name="inputName">excelExportStream</param>
<param name="contentDisposition">attachment;filename="student.xls"</param>
</result>
</action>
</package>
</struts>
3.在Action完成Excel导入
public class TestAction extends ActionSupport {
/**
* 导出Excel
*/
public String excelExport(){
return SUCCESS;
}
//返回streamResult需要的输入流类型
public InputStream getExcelExportStream() throws Exception {
FileDao fileDao = new FileDao();
// 工作簿
HSSFWorkbook book = new HSSFWorkbook();
// 获取工作簿的单元
HSSFSheet sheet = book.createSheet();
// 行后在对应的列
HSSFRow row = sheet.createRow(0);
HSSFCell cellold = row.createCell(0);
HSSFCell cellnew = row.createCell(1);
HSSFCell cellpath = row.createCell(2);
// 单元格-表头
cellold.setCellValue("姓名");
cellnew.setCellValue("性别");
cellpath.setCellValue("年龄");
// 获取实体集合
int i = 1;
Iterator it = fileDao.findAll().iterator();
while (it.hasNext()) {
TImage t = (TImage) it.next();
// 行后在对应的列
HSSFRow rowa = sheet.createRow(i);
HSSFCell cellolda = rowa.createCell(0);
HSSFCell cellnewa = rowa.createCell(1);
HSSFCell cellpatha = rowa.createCell(2);
// 单元格-表头
cellolda.setCellValue(t.getOldname());
cellnewa.setCellValue(t.getNewname());
cellpatha.setCellValue(t.getPathimage());
i++;
}
// 输出流
ByteArrayOutputStream by = new ByteArrayOutputStream();
book.write(by);
return new ByteArrayInputStream(by.toByteArray());
}
}
本文详细介绍了如何在Struts2框架中编写代码实现Excel文件的导出功能,包括在index.xml和struts.xml文件中的配置,以及在Action类中完成Excel数据的导入和生成。
1万+

被折叠的 条评论
为什么被折叠?



