使用poi 打开excel

本文提供了一个使用Java实现的简单示例,演示了如何从服务器导出Excel文件到客户端浏览器,并设置了正确的响应头以便浏览器能够正确处理和显示Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.csland.common.util.*;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class prnexcel
    extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GBK";
  private String url = "D:/test.xls";

  //Initialize global variables
  public void init() throws ServletException {
  }

  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    /**
     * setContentType设置MIME类型,Acrobat
     * PDF文件为"application/pdf",WORD文件为:"application/msword",
     * EXCEL文件为:"application/vnd.ms-excel"。
     */
    //url = Consts.APP_PATH + "statistic/cw/" +
    //    StrUtil.convNull(request.getParameter("excelfile"));

    //url = "E:/ylb.xls";
    System.out.println("url=" + url);
    File file = new File(url);
    System.out.println("fileName=" + file.getName());

    response.setContentType("application/vnd.ms-excel;charset=GBK");
    /**
     * setHeader设置打开方式,具体为:inline为在浏览器中打开,attachment单独打开。
     */

    response.setHeader("Content-disposition",
                       "inline;filename=/"" + file.getName() + "/";");

    OutputStream out = response.getOutputStream();
    POIFSFileSystem fs;
    try {
      fs = new POIFSFileSystem(new FileInputStream(url));
      HSSFWorkbook wb = new HSSFWorkbook(fs);
      HSSFSheet sheet = wb.getSheet("Sheet1");

      wb.write(out);
      out.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }

    //本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/gisoracle/archive/2009/07/03/4318380.aspx

  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    doGet(request, response);
  }

  //Clean up resources
  public void destroy() {
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值