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(); } } //Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //Clean up resources public void destroy() { } }