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

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

(0)

相关推荐

  • Java基于Spire Cloud Excel把Excel转换成PDF

    Spire.Cloud.Excel Sdk 提供GeneralApi接口和WorkbookApi接口,支持将本地Excel和云端Excel文档转换为ODS, PDF, XPS, PCL, PS等格式.本文以将Excel表格转为PDF为例,介绍实现格式转换的步骤及方法. 所需工具:Spire.Cloud.Excel.Sdk 必要步骤: 步骤1:Jar文件下载及导入.可通过"下载中心"下载获取jar:或者通过maven仓库安装导入,具体参考安装方法. 步骤2:ID及Key获取.需要在云端创

  • Java使用jacob将微软office中word、excel、ppt转成pdf

    本文实例为大家分享了Java使用jacob将微软office文档转成pdf的具体代码,供大家参考,具体内容如下 在使用jacb前,我们需要去下载 jacob.jar 和 jacob-1.18-x64.dll 其次,我们需要将jacob-1.18-x64.dll放入到jdk的bin目录下才可以使用 第三,使用jacb之前,我们需要确保office能正常使用 如果你现在使用的是maven工程,那么不好意思,现在还没有发布正式的jacb资源文件,我们需要自定的maven依赖,如下: <dependen

  • Java实现excel表格转成json的方法

    今天有个朋友问我,有没有excel表格到处json的方法,在网上找到了好几个工具,都不太理想,于是根据自己的需求,自己写了一个工具. 功能代码 package org.duang.test; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; impo

  • java实现在线预览--poi实现word、excel、ppt转html的方法

    java实现在线预览 - -之poi实现word.excel.ppt转html,具体内容如下所示: ###简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0 如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools.FlexPaper等)才

  • Java实现的Excel列号数字与字母互相转换功能

    本文实例讲述了Java实现的Excel列号数字与字母互相转换功能.分享给大家供大家参考,具体如下: 我们在实现对Excel的导入导出的时候,往往需要准确的给用户提示信息,提示到具体的Excel的单元格,这里就需要对Excel的列号进行数字和字母的转换,今天正好用到这个需求,所以就写了一个demo,总结一下: Java实现: package test; /** * Deal with Excel column indexToStr and strToIndex * @author Stephen.

  • java POI解析Excel 之数据转换公用方法(推荐)

    如下所示: public static String reThreeStr(String ss){ boolean result= ss.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$"); if(result&&ss!=null&&!"".equals(ss)){ Double sss=Double.valueOf(ss); String numStr=new java

  • Java实现Word/Excel/TXT转PDF的方法

    引言: 前段时间公司做的教育系统,系统需要实时记录用户学习课程的情况和时间,所以对一些除视频课程之外,对一些文本文档型课件同样如此,初次的方案是讲office相关类型的文件进行转换Html文件,然后展示对应的html文件,PC端差不多没问题了,但是个别文件再转换html之后,样式出现了错乱,即时做了编码转换处理,但是还是有个别乱码,最后改变方案,最后统一将文件转为pdf,然后通过流的方式在前端展示,其中包括Word Excel PPT TXT PDF等文件,代码如下: 备注:本来是可以直接展示p

  • java 读取excel文件转换成json格式的实例代码

    需要读取excel数据转换成json数据,写了个测试功能,转换正常: JSON转换:org.json.jar 测试类:  importFile.java: package com.siemens.util; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import org.apache.poi.ss.usermodel.R

  • java生成饼图svg及JFreeChart生成svg图表

    Jfreechart本身不能生成SVG图形,但是可以借助另外一个东西,辅助生成.好像是这个:batik ,具体代码请看下文 一:Java生成svg饼图,附带了一个标签显示各个颜色代表的部分 package com.tellhow.svg; import java.io.File; import java.io.FileOutputStream; /** * * @author 风絮NO.1 * */ public class CakySvgWithLabel { //定义不同的颜色 static

  • Java实现把excel xls中数据转为可直接插入数据库的sql文件

    我的一贯风格,代码说明一切.. 废话不多说了,直接给大家贴代码了,具体代码如下所示: package Tools; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; im

  • java实现excel和txt文件互转

    话不多说,请看代码: import java.io.*; import jxl.*; import jxl.write.*; //用java将txt数据导入excel public class CreateXLS { public static void main(String args[]) { try { //打开文件 WritableWorkbook book= Workbook.createWorkbook(new File("测试.xls")); //生成名为"第一

  • Java 将Excel转为SVG的方法

    1. 程序运行环境如下: 编译工具:IDEA JDK版本:1.8.0 Excel测试文档:.xlsx 2013 Excel工具jar包:free spire.xls.jar 3.9.1 2.关于如何导入jar包 方法1:手动下载jar包.解压,将文件路径:D:\...\Spire.Xls-FE_3.9.1\lib\Spire.Xls.jar中的文件导入Java程序(即本文中使用的方法). 方法2:Maven仓库下载导入.先在maven程序中配置pom.xml文件,如下内容: <repositor

随机推荐