struts开发实践—如何调用excel

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

--文章源自一位网友

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就可以了。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航