首页 > 上网技巧 > 电脑小技巧 > Java POI读取excel

Java POI读取excel

时间:2018-07-11 09:37 作者:QQ地带 我要评论

Java使用Apache POI库读取Excel表格文档的简单示例。
 
import cn.zhikr.wechatshare.businessUserInfo.pojo.FansInfo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * User : Homiss
 * Date : 2017/4/7
 * Time : 17:26
 */
public class XlsxUtil {
  private final static Logger logger = LoggerFactory.getLogger(XlsxUtil.class);
  public static List<FansInfo> getList(String path) throws IOException, InvalidFormatException {
    List<FansInfo> fansInfos = new ArrayList<>();
    Workbook xwb = createworkbook(new FileInputStream(path));
    Sheet sheet = xwb.getSheetAt(0);
    Row row;
    for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
      try {
        row = sheet.getRow(i);
        String name = row.getCell(0) != null ? row.getCell(0).toString() : "";
        String phone = row.getCell(1) != null ? row.getCell(1).toString() : "";
        System.out.println(name + "   " + phone);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return fansInfos;
  }
  public static Workbook createworkbook(InputStream inp)
      throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException {
    if (!inp.markSupported()) {
      inp = new PushbackInputStream(inp, 8);
    }
    if (POIFSFileSystem.hasPOIFSHeader(inp)) {
      return new HSSFWorkbook(inp);
    }
    if (POIXMLDocument.hasOOXMLHeader(inp)) {
      return new XSSFWorkbook(OPCPackage.open(inp));
    }
    throw new IllegalArgumentException("你的excel版本目前poi解析不了");
  }
  public static void main(String[] args) throws IOException, InvalidFormatException {
    getList("C:\\Users\\My\\Desktop\\fans\\health.xls");
  }
}

标签: java
顶一下
(0)
0%
踩一下
(0)
0%

Google提供的广告