java  中Excel转shape file的实例详解

 更新时间:2017年09月08日 14:15:00   投稿:lqh  
这篇文章主要介绍了java 中Excel转shape file的实例详解的相关资料,希望通过本文大家能实现这样的功能,需要的朋友可以参考下

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、对于中文字段,做了取首字母的处理;

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

相关文章

  • mybatis-plus 插入修改配置默认值的实现方式

    mybatis-plus 插入修改配置默认值的实现方式

    这篇文章主要介绍了mybatis-plus 插入修改配置默认值的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Java中不定参数用法小结

    Java中不定参数用法小结

    在Java中,不定参数是指方法的参数数量可以变化的情况,本文主要介绍了Java中不定参数用法,具有一定的参考价值,感兴趣的可以了解一下
    2023-12-12
  • Kryo序列化及反序列化用法示例

    Kryo序列化及反序列化用法示例

    这篇文章主要介绍了Kryo序列化及反序列化用法示例,小编觉得挺不错的,这里分享给大家,需要的朋友可以参考下。
    2017-10-10
  • idea导入项目框架的详细操作方法

    idea导入项目框架的详细操作方法

    大家使用idea开发工具时经常会需要导入项目框架,纠结该怎么操作呢,今天小编给大家分享一篇图文教程,帮助大家解决idea导入项目框架的问题,感兴趣的朋友一起看看吧
    2021-05-05
  • Java总结篇系列:Java泛型详解

    Java总结篇系列:Java泛型详解

    下面小编就为大家带来一篇Java总结篇系列:Java泛型详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-09-09
  • Java开源诊断工具Arthas使用方法详解

    Java开源诊断工具Arthas使用方法详解

    这篇文章主要介绍了Java开源诊断工具Arthas使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • Java实现常见的排序算法代码实例

    Java实现常见的排序算法代码实例

    这篇文章主要介绍了Java实现常见的排序算法代码实例,按照思路实现了以下几个排序算法(冒泡排序、直接插入排序、直接选择排序、快速排序),方便日后用到,特此记录一下,需要的朋友可以参考下
    2023-11-11
  • Java框架设计灵魂之反射的示例详解

    Java框架设计灵魂之反射的示例详解

    反射就是把Java类中的各个成员映射成一个个的Java对象。本文将通过示例为大家详细讲解Java框架设计的灵魂:反射,感兴趣的可以了解一下
    2022-06-06
  • Java中ArrayList和LinkedList区别

    Java中ArrayList和LinkedList区别

    这篇文章主要介绍了Java中ArrayList和LinkedList区别,下面我们就重点聊一聊在日常开发中经常被使用到的两个集合类ArrayList和LinkedList的本质区别吧,需要的朋友可以参考一下
    2022-01-01
  • 通过Java实现在Word中创建可填充表单

    通过Java实现在Word中创建可填充表单

    这篇文章主要为大家详细介绍了如何通过Java代码,以编程方式在Word中创建可填充表单,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2023-03-03

最新评论