--文章源自一位网友
这篇文章是一个叫smilelily网友写的,昨天找自己的email记录找到了,他在csdn上有用户,文章源地址
http://dev.csdn.net/user/smilelily
struts开发实践—如何调用excel
1. 首先去http://jakarta.apache.org/poi/网站下载poi包。我使用的版本为:jakarta-poi-1.9.0-dev-20030219。网站上还有相应的文档,可以学习一下。
2. 将下载的包放在WEB-INF/lib目录下。
3. 写调用Excel的ACTION,example code如下:
package test;
import org.apache.struts.action.*;
import java.io.*;
import javax.servlet.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
/**
* 写excel文件
*/
public class TestExcelAction
extends Action {
private static final String CONTENT_TYPE = "application/vnd.ms-excel";
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
response.setContentType(CONTENT_TYPE);
ActionErrors errors = new ActionErrors();
try {
//内容
try {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFHeader header = sheet.getHeader();
header.setCenter("工资报表");
HSSFRow row1 = sheet.createRow( (short) 0);
HSSFCell cell11 = row1.createCell( (short) 0);
cell11.setEncoding(HSSFCell.ENCODING_UTF_16);
cell11.setCellValue("编号");
HSSFCell cell12 = row1.createCell( (short) 1);
cell12.setEncoding(HSSFCell.ENCODING_UTF_16);
cell12.setCellValue("部门");
HSSFCell cell13 = row1.createCell( (short) 2);
cell13.setEncoding(HSSFCell.ENCODING_UTF_16);
cell13.setCellValue("姓名");
HSSFCell cell14 = row1.createCell( (short) 3);
cell14.setEncoding(HSSFCell.ENCODING_UTF_16);
cell14.setCellValue("应发工资");
HSSFCell cell15 = row1.createCell( (short) 4);
cell15.setEncoding(HSSFCell.ENCODING_UTF_16);
cell15.setCellValue("基本工资");
HSSFCell cell16 = row1.createCell( (short) 5);
cell16.setEncoding(HSSFCell.ENCODING_UTF_16);
cell16.setCellValue("岗位工资");
HSSFCell cell17 = row1.createCell( (short) 6);
cell17.setEncoding(HSSFCell.ENCODING_UTF_16);
cell17.setCellValue("奖金");
sheet.setGridsPrinted(true);
HSSFFooter footer = sheet.getFooter();
footer.setRight("Page " + HSSFFooter.page() + " of " +
HSSFFooter.numPages());
ServletOutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
}
catch (Exception e) {
System.out.println("error in JSP");
}
return null;
}
catch (Throwable e) {
e.printStackTrace();
ActionError error = new ActionError(e.getMessage());
errors.add(ActionErrors.GLOBAL_ERROR, error);
}
saveErrors(request, errors);
return new ActionForward(mapping.getInput());
}
}
4。调用这个testExcelAction就可以了。