struts开发实践—如何调用excel

类别:Java 点击:0 评论:0 推荐:

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

本文地址:http://com.8s8s.com/it/it16624.htm