poi读取excel并输出到jsp页面
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
代码来源于网络,只做了部分修改,我也是刚用到很多都不懂,找了一些例子之类的自己用,有些不错的分享给大家,仅供参考。
下面这个是用servlet做(注意web.xml );其实原理一样;源码如下
readExcelServlet.java
package com.test.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ermodel.HSSFCell;
import ermodel.HSSFDateUtil;
import ermodel.HSSFRow;
import ermodel.HSSFSheet;
import ermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* author:wx * describe:Reads the Excel example *
*/
public class readExcelServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* * Constructor of the object.
*/
public readExcelServlet() {
super();
}
/**
* Destruction of the servlet.
*
*/
public void destroy() {
super.destroy();
}// Just puts "destroy" string in log
// Put your code here
/**
* doGet
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* doPost
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String filePath = new String(request.getParameter("file").getBytes(
"GBK"), "gb2312");//注意如果这里出现乱码导致文件路径错误试着改下GBK,换成ISO-8859-1
out.print("文件路径:" + filePath + "
");
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
filePath));
// 创建工作簿
HSSFWorkbook workBook = new HSSFWorkbook(fs);
/**
* 获得Excel中工作表个数
*/
out.println("工作表个数 :" + workBook.getNumberOfSheets() + "
");
for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
out.println(" " + i
+ " ***************工作表名称:"+ workBook.getSheetName(i)
+ " ************
");
// 创建工作表
HSSFSheet sheet = workBook.getSheetAt(i);
int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
if (rows > 0) {
sheet.getMargin(HSSFSheet.TopMargin);
for (int j = 0; j < rows; j++) { // 行循环
HSSFRow row = sheet.getRow(j);
if (row != null) {
int cells = row.getLastCellNum();// 获得列数
for (short k = 0; k < cells; k++) { // 列循环
HSSFCell cell = row.getCell(k);
if (cell != null) {
String value = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: