当前位置: 移动技术网 > IT编程>开发语言>Java > java 中Excel转shape file的实例详解

java 中Excel转shape file的实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论
java  中excel转shape file的实例详解 概述: 本文讲述如何结合geotools和poi实现excel到shp的转换,再结合前文shp到

java  中excel转shape file的实例详解

概述:

本文讲述如何结合geotools和poi实现excel到shp的转换,再结合前文shp到geojson数据的转换,即可实现用户上传excel数据并在web端的展示功能。

截图:

 原始excel文件

运行耗时

运行结果

代码:

package com.lzugis.geotools;

import com.lzugis.commonmethod;
import com.vividsolutions.jts.geom.coordinate;
import com.vividsolutions.jts.geom.geometryfactory;
import com.vividsolutions.jts.geom.point;
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;
import org.apache.poi.poifs.filesystem.poifsfilesystem;
import org.geotools.data.featurewriter;
import org.geotools.data.transaction;
import org.geotools.data.shapefile.shapefiledatastore;
import org.geotools.data.shapefile.shapefiledatastorefactory;
import org.geotools.feature.simple.simplefeaturetypebuilder;
import org.geotools.referencing.crs.defaultgeographiccrs;
import org.opengis.feature.simple.simplefeature;
import org.opengis.feature.simple.simplefeaturetype;

import java.io.file;
import java.io.fileinputstream;
import java.io.inputstream;
import java.io.serializable;
import java.nio.charset.charset;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;

/**
 * created by admin on 2017/9/6.
 */
public class xls2shape {
  static xls2shape xls2shp = new xls2shape();
  private static string rootpath = system.getproperty("user.dir");
  private commonmethod cm = new commonmethod();

  private hssfsheet sheet;

  private class getcelltype(hssfcell cell) {
    if (cell.getcelltype() == hssfcell.cell_type_string) {
      return string.class;
    } else if (cell.getcelltype() == hssfcell.cell_type_numeric) {
      return double.class;
    } else {
      return string.class;
    }
  }

  private object getcellvalue(hssfcell cell) {
    if (cell.getcelltype() == hssfcell.cell_type_string) {
      return cell.getrichstringcellvalue().getstring();
    } else if (cell.getcelltype() == hssfcell.cell_type_numeric) {
      return cell.getnumericcellvalue();
    } else {
      return "";
    }
  }

  private list<map<string, object>> getexcelheader() {
    list<map<string, object>> list = new arraylist();
    hssfrow header = sheet.getrow(0);
    hssfrow value = sheet.getrow(1);
    //获取总列数
    int colnum = header.getphysicalnumberofcells();
    for (int i = 0; i < colnum; i++) {
      hssfcell cellfield = header.getcell(i);
      hssfcell cellvalue = value.getcell(i);
      string fieldname = cellfield.getrichstringcellvalue().getstring();
      fieldname = cm.getpinyinheadchar(fieldname);
      class fieldtype = getcelltype(cellvalue);
      map<string, object> map = new hashmap<string, object>();
      map.put("name", fieldname);
      map.put("type", fieldtype);
      list.add(map);
    }
    return list;
  }

  public void excel2shape(string xlsfile, string shppath) {
    poifsfilesystem fs;
    hssfworkbook wb;
    hssfrow row;
    try {
      inputstream is = new fileinputstream(xlsfile);
      fs = new poifsfilesystem(is);
      wb = new hssfworkbook(fs);
      sheet = wb.getsheetat(0);
      //获取总列数
      int colnum = sheet.getrow(0).getphysicalnumberofcells();
      // 得到总行数
      int rownum = sheet.getlastrownum();

      list list = getexcelheader();
      //创建shape文件对象
      file file = new file(shppath);
      map<string, serializable> params = new hashmap<string, serializable>();
      params.put(shapefiledatastorefactory.urlp.key, file.touri().tourl());
      shapefiledatastore ds = (shapefiledatastore) new shapefiledatastorefactory().createnewdatastore(params);
      //定义图形信息和属性信息
      simplefeaturetypebuilder tb = new simplefeaturetypebuilder();
      tb.setcrs(defaultgeographiccrs.wgs84);
      tb.setname("shapefile");
      tb.add("the_geom", point.class);
      for (int i = 0; i < list.size(); i++) {
        map<string, object> map = (map<string, object>) list.get(i);
        tb.add(map.get("name").tostring(), (class) map.get("type"));
      }
      ds.createschema(tb.buildfeaturetype());
      //设置编码
      charset charset = charset.forname("gbk");
      ds.setcharset(charset);
      //设置writer
      featurewriter<simplefeaturetype, simplefeature> writer = ds.getfeaturewriter(ds.gettypenames()[0], transaction.auto_commit);
      //写下一条
      simplefeature feature = null;
      for (int i = 1; i < rownum; i++) {
        row = sheet.getrow(i);
        feature = writer.next();
        map maplonlat = new hashmap();
        for (int j = 0; j < colnum; j++) {
          hssfcell cell = row.getcell(j);
          map<string, object> mapfields = (map<string, object>) list.get(j);
          string fieldname = mapfields.get("name").tostring();
          feature.setattribute(fieldname, getcellvalue(cell));
          if (fieldname.tolowercase().equals("lon") || fieldname.tolowercase().equals("lat")) {
            maplonlat.put(fieldname, getcellvalue(cell));
          }
        }
        feature.setattribute("the_geom", new geometryfactory().createpoint(new coordinate((double) maplonlat.get("lon"), (double) maplonlat.get("lat"))));
      }
      writer.write();
      writer.close();
      ds.dispose();

    } catch (exception e) {
      e.printstacktrace();
    }
  }

  public static void main(string[] args) {
    long start = system.currenttimemillis();
    string xlspath = rootpath + "/data/xls/capital.xls",
        shppath = rootpath + "/out/capital.shp";
    xls2shp.excel2shape(xlspath, shppath);
    system.out.println("共耗时" + (system.currenttimemillis() - start) + "ms");
  }
}

说明:

1、转换仅限点对象的转换;
2、保留所有excel相关的属性,lon、lat字段是必须要有的;
3、对于中文字段,做了取首字母的处理;

 如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网