C#版本GDAL创建图层文件
1.下面是代码是通过一个有x,y坐标字段的Excel文件创建一个PostGIS中的表
2.如果希望创建一个Shapefile文件,或者其他方式表示的图层,流程基本一致。只是在获取GetDriverByName的时候换成你希望的drivers,比如Shapefile则改为:
OSGeo.OGR.Driver fileDriver = Ogr.GetDriverByName("ESRI Shapefile");
var fileDs = fileDriver.CreateDataSource(fileTempPath, new string[]{ "ENCODING=UTF-8"});//这里的fileTempPath是一个文件夹路径
3.代码:
var file = new FileInfo(filePath);//filePath是excel文件的路径,这里的excel文件后缀需要是xlsx
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(file))//使用ExcelPackage打开excel文件读取字段
{
var sheet = package.Workbook.Worksheets[0];
var rowCount = sheet.Dimension.Rows;
var colCount = sheet.Dimension.Columns;
var xIndex = 0;
var yIndex = 0;
if (rowCount * colCount != 0)
{
for (var i = 1; i <= colCount; i++)
{
if (sheet.Cells[1, i].Value.ToString()==input.XField)//获取x字段的index
{
xIndex = i;
continue;
}
if (sheet.Cells[1, i].Value.ToString() == input.YField)//获取y字段的index
{
yIndex = i;
continue;
}
}
}
Gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8");
GdalBase.ConfigureAll();
var pgConnectStr = $"PG:dbname={_postGISConnectOption.Database} host={_postGISConnectOption.Host} port={_postGISConnectOption.Port} user={_postGISConnectOption.UserId} password={_postGISConnectOption.Password}";
OSGeo.OGR.Driver pgDriver = Ogr.GetDriverByName("PostgreSQL");
var pgDs = pgDriver.Open(pgConnectStr, 1);
var layerName = $"{Clock.Now.ToString("yyyyMMddHHmmss")}{Path.GetFileNameWithoutExtension(input.FileName)}";
var spatial = new OSGeo.OSR.SpatialReference("");//这里是创建一个坐标系
spatial.SetWellKnownGeogCS($"EPSG:{input.ESPG}");//input.ESPG的值是4326
var newLayer = pgDs.CreateLayer(layerName, spatial, wkbGeometryType.wkbPoint, new string[] {"ENCODING=UTF-8" });//创建一个图层,集合类型是wkbPoint
newLayer.StartTransaction();
for (var i = 1; i <= colCount; i++)//获取excel的第一行作为字段名称,这里将全部字段都设置为string类型
{
newLayer.CreateField(new FieldDefn(sheet.Cells[1, i].Value.ToString(),FieldType.OFTString),1);
}
for (var i =2;i<=rowCount;i++)//依次每行创建一个feature加入到上面创建的layer中即可
{
var newFeature = new Feature(newLayer.GetLayerDefn());
for (int j = 1; j < colCount; j++)
{
newFeature.SetField(j, sheet.Cells[i,j].Value==null?"": sheet.Cells[i, j].Value.ToString());
}
var geo = new Geometry(wkbGeometryType.wkbPoint);//创建几何点字段
geo.AddPoint_2D((double)sheet.Cells[i, xIndex].Value, (double)sheet.Cells[i, yIndex].Value);
newFeature.SetGeometry(geo);
newLayer.CreateFeature(newFeature);
}
newLayer.CommitTransaction();
}