关闭

java读取Excel文件.

362人阅读 评论(0) 收藏 举报

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html; charset=utf-8");
  request.setCharacterEncoding("UTF-8");
  PrintWriter out = response.getWriter();
  out.print(execute(request));
  out.close();
 }

 @SuppressWarnings("unchecked")
 public String execute(HttpServletRequest request) {

  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  JSONObject obj = new JSONObject();
  try {
   List items = upload.parseRequest(request);

   for (Iterator i = items.iterator(); i.hasNext();) {
    FileItem fi = (FileItem) i.next();
    String fileName = fi.getName();
    
    if (null == fileName) {
    } else {
     String extension = fileName.lastIndexOf(".")== -1 ? "": fileName.substring(fileName.lastIndexOf(".")+ 1);
     InputStream is = fi.getInputStream();

     Iterator<Row> iterRow = null;

     if("xls".equalsIgnoreCase(extension)){
      // offices 2003
      HSSFWorkbook hwb = new HSSFWorkbook(is);
      HSSFSheet hsheet = hwb.getSheetAt(0);
      iterRow = hsheet.rowIterator();
     }else if(("xlsx").equalsIgnoreCase(extension)){
      // offices 2007
      XSSFWorkbook xwb = new XSSFWorkbook(is);
      XSSFSheet xsheet = xwb.getSheetAt(0);
      iterRow = xsheet.rowIterator();
     }else {
      isSuccess = false;
      obj.put("success", isSuccess);
      obj.put("msg", "导入文件格式不正确,请上传Excel文件!");
      is.close();
      return obj.toString();
     }

 

     for (Iterator<Row> iter1 = iterRow; iter1.hasNext();) {
      Row row = iter1.next();
      if (row.getRowNum() > 0) {
        // 迭代列
       for (Iterator<Cell> iter2 = (Iterator<Cell>) row
         .cellIterator(); iter2.hasNext();) {
        Cell cell = iter2.next();
        String value = cell.getStringCellValue();
               if (cell.getColumnIndex() == 2) {
                      .....

        } else if (cell.getColumnIndex() == 3) {
        ....

        } else if (cell.getColumnIndex() == 6) {
         ....        }
       }      }
     }
     is.close();

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:215156次
    • 积分:2707
    • 等级:
    • 排名:第13815名
    • 原创:50篇
    • 转载:55篇
    • 译文:0篇
    • 评论:24条
    最新评论