无需上传附件到服务器,Servlet读取Excel(二)
package com.str;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadExcel extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
byte[] junk = new byte[1024];
int bytesRead = 0;
ServletInputStream is = req.getInputStream();
// shou首先除去Http Head
bytesRead = is.readLine(junk,0,junk.length);
bytesRead = is.readLine(junk,0,junk.length);
bytesRead = is.readLine(junk,0,junk.length);
bytesRead = is.readLine(junk,0,junk.length);
HSSFWorkbook wb = new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt(0);
for(int j=0;j< sheet .getLastRowNum()+1;j++) {
//创建一个行对象
HSSFRow row = sheet.getRow(j);
//把一行里的每一个字段遍历出来
for(int i=0;i<row.getLastCellNum();i++) {
//创建一个行里的一个字段的对象,也就是获取到的一个单元格中的值
HSSFCell cell = row.getCell(i);
//在这里我们就可以做很多自己想做的操作了,比如往数据库中添加数据等
System.out.print(cell.toString() + " " );
}
System.out.println(" ");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}