您的位置:首页 > 编程语言 > Java开发

java使用poi实现excel解析

2013-05-20 11:57 141 查看
上传文件本地路径自从ie8之后是无法从程序中获取的,因为ie加了权限保护,程序上传文件时会先默认c盘创建临时文件来引导文件流的读取,而不是直接获取全路径来读取文件。如果想从action的file对象中获取的路径并根据这个路径判断其文件类型、是没法根据其后缀名判断的,因为这个临时文件是.temp类型,所以要就在判断文件类型时使用fileFileName得到全文件名去判断文件类型,使用file.getPath()进行文件读取。

jsp:

  <s:form action="pages/BatchExcel/InitBatchExcel.html" method="POST"

   enctype="multipart/form-data">

   <s:file name="batchexcel" label="批量添加公司" />

   <s:submit value="批量上传" />

  </s:form>

 

action类:

List<List<String>> list = poi.read(batchexcel.getPath(),batchexcelFileName);

 

ReadExcel类:

public List<List<String>> read(String filePath,String filePathFileName) {

  List<List<String>> dataLst = new ArrayList<List<String>>();

  InputStream is = null;

  try {

   if (!validateExcel(filePathFileName)) {

    return null;

   }

   if (!validateExcelExists(filePath)) {

    return null;

   }

   boolean isExcel2003 = true;

   if (WDWUtil.isExcel2007(filePath)) {

    isExcel2003 = false;

   }

   File file = new File(filePath);

   is = new FileInputStream(file);

   dataLst = read(is, isExcel2003);

   is.close();

  } catch (Exception ex) {

   ex.printStackTrace();

  } finally {

   if (is != null) {

    try {

     is.close();

    } catch (IOException e) {

     is = null;

     e.printStackTrace();

    }

   }

  }

  return dataLst;

 }

 

public boolean validateExcel(String filePathFileName) {

  if (filePathFileName == null

    || !(WDWUtil.isExcel2003(filePathFileName) || WDWUtil

      .isExcel2007(filePathFileName))) {

   errorInfo = "文件名不是excel格式";

   return false;

  }

  return true;

 }

 public boolean validateExcelExists(String filePath) {

  File file = new File(filePath);

  if (file == null || !file.exists()) {

   errorInfo = "文件不存在";

   return false;

  }

  return true;

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java poi excel