文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java  中Excel转shape file的实例详解

2023-05-31 05:00

关注

java  中Excel转shape file的实例详解

概述:

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

截图:

java  中Excel转shape file的实例详解

 原始Excel文件

java  中Excel转shape file的实例详解

运行耗时

java  中Excel转shape file的实例详解

运行结果

代码:

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;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");  }}

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯