Java读取Excel

  1. import java.io.File;   
  2. import java.sql.Connection;   
  3. import javax.servlet.ServletContext;   
  4. import javax.servlet.ServletException;   
  5. import javax.servlet.http.HttpServletRequest;   
  6. import javax.servlet.http.HttpServletResponse;   
  7.   
  8. import jxl.Cell;   
  9. import jxl.CellType;   
  10. import jxl.DateCell;   
  11. import jxl.NumberCell;   
  12. import jxl.Sheet;   
  13. import jxl.Workbook;   
  14.   
  15. import com.xxx.exception.SystemException;   
  16. import com.xxx.web.IAction;   
  17.   
  18. public class CaseQueryAction implements IAction{   
  19.   
  20.     public CaseQueryAction() {   
  21.   
  22.     }   
  23.   
  24.     public void perform(   
  25.         HttpServletRequest request,   
  26.         HttpServletResponse response,   
  27.         ServletContext context,   
  28.         Connection connection)   
  29.         throws ServletException, SystemException {   
  30.   
  31.         Workbook workbook = null;   
  32.   
  33.         try {   
  34.             workbook = Workbook.getWorkbook(new File("d:\\temp\\TestRead.xls"));   
  35.         } catch (Exception e) {   
  36.             try {   
  37.                 throw new Exception("file to import not found!");   
  38.             } catch (Exception e1) {   
  39.                 e1.printStackTrace();   
  40.             }   
  41.         }   
  42.   
  43.         Sheet sheet = workbook.getSheet(0);   
  44.         Cell cell = null;   
  45.   
  46.         int columnCount=3;   
  47.         int rowCount=sheet.getRows();   
  48.         for (int i = 0; i <rowCount; i++) {   
  49.             for (int j = 0; j <columnCount; j++) {   
  50.                 //注意,这里的两个参数,第一个是表示列的,第二才表示行   
  51.                 cell=sheet.getCell(j, i);   
  52.                 //要根据单元格的类型分别做处理,否则格式化过的内容可能会不正确   
  53.                 if(cell.getType()==CellType.NUMBER){   
  54.                     System.out.print(((NumberCell)cell).getValue());   
  55.                 }else if(cell.getType()==CellType.DATE){   
  56.                     System.out.print(((DateCell)cell).getDate());   
  57.                 }else{   
  58.                     System.out.print(cell.getContents());   
  59.                 }   
  60.                 //System.out.print(cell.getContents());   
  61.                 System.out.print("\t");   
  62.             }   
  63.             System.out.print("\n");   
  64.         }   
  65.         //关闭它,否则会有内存泄露   
  66.         workbook.close();   
  67.     }   
  68. }  
  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓