概述:

本文讲述如何结合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);//设置WriterFeatureWriter<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、对于中文字段,做了取首字母的处理;

-----------------------------------------------------------------------------------------------


如果我的文章对您有帮助,谢谢支持!

技术博客CSDN:http://blog.csdn.NET/gisshixisheng博客园:http://www.cnblogs.com/lzugis/
在线教程http://edu.csdn.Net/course/detail/799Githubhttps://github.com/lzugis/联系方式q       q:1004740957e-mail:niujp08@qq.com公众号:lzugis15Q Q 群:452117357(webgis)             337469080(Android)

Excel转shape file相关推荐

  1. shape file与coverage叠加的问题

    为什么SHP和COV可以直接叠加? 今天在和网友讨论问题后,自己做了一下,正好碰上这个问题.两种不同格式的文件怎么能无缝的叠加呢? 是不是ARCGIS在处理时内部将SHP转为了COV,然后叠加后,再转 ...

  2. Java SHA-256加密的两种实现方法详解

    利用Apache的工具类实现加密,使用commons-codec包中的DigestUtils算法工具类(入参支持字符串.字节数组.文件流等): maven: 1 2 3 4 5 <depende ...

  3. PHP 导出Excel 报错:realpath(): open_basedir restriction in effect. File(/tmp) is not within the allowed

    PHP 导出Excel 报错:realpath(): open_basedir restriction in effect. File(/tmp) is not within the allowed  ...

  4. 关于excel导入带图片

    public String importExcel(MultipartFile file) {if (file == null) {throw new CustomException("当前 ...

  5. java实现excel导入导出,对象图片读取,上传七牛云

    java实现excel导入导出以及解决方案 因为公司业务需求,要完成针对表格的导入导出,excel这里使用MultipartFile类接收 ,下面是部分关键代码,希望有所帮助 //获取excel文件的 ...

  6. 使用POI对excel文件进行读取

    使用POI对excel文件进行读取 Excel转换为HTML表格(包括样式) Excel读取图片 Excel读取附件 使用POI对excel文件进行读取 excel转换HTML 代码块 ReadExc ...

  7. 导出地图 | EXCEL批量导出ShapeFile、GeoJSON、KLM等格式

    1 需求 EXCEL作为办公利器,广泛应用于工作和学习处理数据的场景中. 对于地理相关专业的工作,经常需要接触大量带有坐标的表格数据,需要将表格数据转换为ShapeFile格式的文件,再应用于专业GI ...

  8. Java带图片的excel数据导入

    带图片的EXCEL数据导入 这里使用的是POI,所以这里使用的很杂,不过方便对它们的了解.模板下载与图片导出到excel都不一样. 下面会把对应连接贴上. 带入依赖:不要使用3.17的版本,直接上代码 ...

  9. python处理Excel(1):报表结构转换处理各经联社收支明细表(支出项目汇总表)

    python处理Excel:报表结构转换处理各经联社收支明细表(支出项目汇总表) 一. #coding=utf-8 #Transformation structure报表结构转换 import xlr ...

  10. NPOI读写Excel

    1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...

最新文章

  1. JMeter性能测试,验证请求数据的准确性(wc命令)
  2. 执行Shell脚本的4种方法
  3. 2017年山东省ACM省赛总结
  4. python 矩阵库_NumPy 矩阵库(Matrix)
  5. Python项目中 封装日志模块logging 及快速调用方法
  6. VDUSE(vDPA Device in Userspace)技术简介
  7. GB/T 10595-2017版标准的错别字
  8. 设计HTML标签title属性值换行
  9. avast6.0网络安全软件破解至2050年_avast激活码_avast有效激活
  10. SSL基础:12:查询证书详细信息
  11. 【bzoj3144 切糕】
  12. M个苹果放N个篮子,篮子可以为空,有多少种放法?
  13. 前端接收pdf文件_前端实现PDF导出功能
  14. 一个小型VC项目的开发
  15. 社交电商难定义,蘑菇街、小红书、拼多多注定要兵分三路?
  16. LSTM和GRU的对比和分析
  17. 字符串使用split()方法截取时的空字符串问题
  18. WorldFirst公布本地化品牌名称,跨境收款万里汇!
  19. [转帖]ASML发布Q1季度财报 营收22.3亿欧元,EUV光刻机下半年产能大增 ...
  20. python远程使用ants中的配准命令和N4biasfiledcorrection注意点

热门文章

  1. nextjs的发布,pm2发布nextjs项目
  2. 2021/4/27 “如何为div层添加边框?”(border属性详解)
  3. kettle org.pentaho.ui.xul.XulException: java.lang.reflect.InvocationTargetException
  4. WPS word解决公式上浮的问题
  5. 群晖存储服务器虚拟机,安装黑群晖DSM6.2.1完整教程(虚拟机VMWARE15)
  6. C++后台开发学习路线
  7. php使用加密狗,加密狗使用方法
  8. 图的存储结构——邻接表
  9. php怎么在excel表格中输出换行,Excel表格怎么换行打字
  10. awesome系列网址