using System.Data; using System.Reflection.PortableExecutable; using ClosedXML.Excel; using System.Text.Json.Nodes; using Infrastructure; using Infrastructure.Utils; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using NetTopologySuite; using NetTopologySuite.Geometries; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using OpenAuth.App.BaseApp.Base; using OpenAuth.App.FormModule; using OpenAuth.App.Interface; using OpenAuth.App.ServiceApp.LayerManagerApp.Request; using OpenAuth.Repository; using OpenAuth.Repository.Domain; using SqlSugar; using DocumentFormat.OpenXml.Bibliography; using OpenAuth.App.Request; using System.IO; using DocumentFormat.OpenXml.Math; namespace OpenAuth.App.ServiceApp.LayerManagerApp; public class LayerApp : SqlSugarBaseApp { private readonly string _filePath; private readonly ISqlSugarClient _client; public LayerApp(ISugarUnitOfWork unitWork, ISimpleClient repository, IAuth auth, IOptions setOptions, ISqlSugarClient client) : base(unitWork, repository, auth) { _client = client; _filePath = setOptions.Value.UploadPath; if (string.IsNullOrEmpty(_filePath)) { _filePath = AppContext.BaseDirectory; } } public async Task> UploadExcel(LayerReq req) { using var db = Repository.AsSugarClient(); var excelPath = Path.Combine(_filePath, req.FilePath); // excel名称 var excelFileName = Path.GetFileNameWithoutExtension(excelPath); // 使用NPOI读取Excel文件 using (var fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook; if (Path.GetExtension(excelPath).Equals(".xls")) { workbook = new HSSFWorkbook(fileStream); } else { workbook = new XSSFWorkbook(fileStream); } // var sheet = workbook.GetSheetAt(0); // 获取总行数 var rowCount = sheet.LastRowNum; if (rowCount < 3) { throw new Exception("只有两行表头"); } // 获取总列数 var columnCount = sheet.GetRow(0).LastCellNum; var headers = new List(); // 遍历表头 var chineseRow = sheet.GetRow(0); var englishRow = sheet.GetRow(1); for (var j = 0; j < columnCount; j++) { var header = new DataTableAttr { InitName = chineseRow.GetCell(j).ToString(), // 中文表头 RefName = englishRow.GetCell(j).ToString()?.ToLower(), // 英文表头 // 字段类型 Type = "string", // 原始字段名称 Name = englishRow.GetCell(j).ToString(), // 字段长度 Length = 64 }; headers.Add(header); } var keys = headers.Select(a => a.RefName).ToList(); if (!keys.Contains("lng") || !keys.Contains("lat")) { throw new Exception("缺少经纬度字段"); } var typeBuilder = db.DynamicBuilder().CreateClass(req.DataTable, new SugarTable() { TableName = req.DataTable, TableDescription = req.ServerName + "图斑" }); //添加主键 typeBuilder.CreateProperty("id", typeof(string), new SugarColumn() { IsPrimaryKey = true, IsIdentity = false, ColumnDataType = "varchar", Length = 36, ColumnDescription = "主键", }); //添加主键 typeBuilder.CreateProperty("geometry", typeof(string), new SugarColumn() { IsPrimaryKey = false, IsIdentity = false, // ColumnDataType = "geometry(GEOMETRY)", ColumnDataType = string.Concat("geometry(GEOMETRY,", req.SpatialRef.AsSpan(req.SpatialRef.LastIndexOf(":", StringComparison.Ordinal) + 1), ")"), ColumnDescription = "图斑", }); headers.ForEach(u => { if (!u.RefName.Equals("lng") && !u.RefName.Equals("lat")) { typeBuilder.CreateProperty(u.RefName, typeof(string), new SugarColumn() { IsPrimaryKey = false, IsIdentity = false, IsNullable = true, Length = u.Length, ColumnDescription = u.InitName, }); } }); // 开启事务 await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted); // 创建表 //db.CodeFirst.InitTables(typeBuilder.BuilderType()); var cols = new string[headers.Count]; for (var i = 0; i < headers.Count; i++) { if (headers[i].RefName.Equals("lng")) { cols[i] = "geometry"; } else if (headers[i].RefName.Equals("lat")) { cols[i] = "id"; } else { cols[i] = headers[i].RefName; } } var objs = new List>(1001); var num = 0; // 遍历数据行 for (var i = 2; i < rowCount; i++) { var row = sheet.GetRow(i); if (row == null) { continue; } var data = new Dictionary(); // 遍历列 string lat = null, lng = null; for (var j = 0; j < columnCount; j++) { var cell = row.GetCell(j); if (cell == null) { continue; } var cellValue = cell.ToString(); switch (headers[j].RefName) { case "lat": lat = cellValue; continue; case "lng": lng = cellValue; continue; default: data[headers[j].RefName] = cellValue; break; } } if (lat != null && lng != null) { var geography = NtsGeometryServices.Instance.CreateGeometryFactory( int.Parse(req.SpatialRef.Substring( req.SpatialRef.IndexOf(":", StringComparison.Ordinal) + 1))); var point = geography.CreatePoint(new Coordinate(double.Parse(lng), double.Parse(lat))); data["geometry"] = point.AsText(); } data["id"] = Guid.NewGuid().ToString(); objs.Add(data); if (num++ == 999) { await db.Insertable(objs) .AS(req.DataTable) // 指定目标表名 .InsertColumns(cols) // 指定要插入的列 .ExecuteCommandAsync(); num = 0; objs.Clear(); } } await db.Insertable(objs) .AS(req.DataTable) // 指定目标表名 .InsertColumns(cols) // 指定要插入的列 .ExecuteCommandAsync(); await db.Ado.CommitTranAsync(); workbook.Close(); // 关于图层发布失败后,如何处理? // excel 矢量点发布图层 var response = await GeoUtil.CreateStoreAndLayer("", req.SpatialRef, req.DataTable, ""); // todo 保存图层信息 var dmLayer = new DmLayer() { Id = Guid.NewGuid().ToString(), SeverName = req.ServerName, SpatialRef = req.SpatialRef, SeverType = req.SeverType, // 服务类型 StoreType = "", //存储类型 DataSourceType = req.DataSourceType, TableRef = req.DataTable, ShapeType = req.ShapeType, StyleName = req.StyleName, // 样式名称 Description = req.Description, // 描述 Screenshot = req.Screenshot // 截图 }; await Repository.AsSugarClient().Insertable(dmLayer).ExecuteCommandAsync(); } return new Response { Result = true }; } public async Task> UploadShape(LayerReq req) { try { } catch (Exception ex) { throw new CommonException(ex.Message, 500); } return new Response { Result = true }; } public Response> TableDataByTableName(string tablename, string type, string keyword, string keyvalue, int page, int pagesize) { Dictionary result = new Dictionary(); string sql = $"select column_name as name from INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'public' AND table_name ='" + tablename + "'"; var cloumnlist = _client.Ado.SqlQuery(sql); result.Add("head", cloumnlist); string names = ""; string geoms = ""; for (int i = 0; i < cloumnlist.Count; i++) { var name = cloumnlist[i]; if (name.Contains("geom")) { geoms = name; } else { names = names +"\""+ name + "\","; } } string sql1 = $"select " + names + "ST_AsText(" + geoms + ") as " + geoms + $" from " + tablename + " where 1=1 "; if (string.IsNullOrEmpty(keyword) || string.IsNullOrEmpty(keyvalue)) { sql1 = sql1 + "limit "+ pagesize + " offset "+(page-1)*pagesize; } else { sql1 = sql1 + " and " + keyword + " like '%" + keyvalue + "%'" + "limit " + pagesize + " offset " + (page - 1) * pagesize; } var result1 = _client.Ado.SqlQuery(sql1); result.Add("data", result1); return new Response> { Result = result }; } public Response TempeleteByTableName(string tablename) { Response response = new Response(); string sql = $"select column_name as name from INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'public' AND table_name ='" + tablename + "'"; var cloumnlist = _client.Ado.SqlQuery(sql); try { HSSFWorkbook workbook = new HSSFWorkbook(); IFont font = workbook.CreateFont(); //创建一个字体样式对象 font.FontName = "Microsoft YaHei"; //和excel里面的字体对应 font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗 font.FontHeightInPoints = 12; //字体大小 ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象 style1.BorderBottom = BorderStyle.Thin; style1.BorderLeft = BorderStyle.Thin; style1.BorderRight = BorderStyle.Thin; style1.BorderTop = BorderStyle.Thin; style1.Alignment = HorizontalAlignment.Center; style1.VerticalAlignment = VerticalAlignment.Center; style1.SetFont(font); //将字体样式赋给样式对象 // 创建一个数值格式的CellStyle ICellStyle numericStyle = workbook.CreateCellStyle(); // 创建一个数据格式对象 IDataFormat dataFormat = workbook.CreateDataFormat(); var font11 = workbook.CreateFont(); font11.FontName = "Microsoft YaHei"; font11.FontHeightInPoints = 12; // 设置单元格格式为数值型 numericStyle.DataFormat = dataFormat.GetFormat("0.00"); numericStyle.BorderBottom = BorderStyle.Thin; numericStyle.BorderLeft = BorderStyle.Thin; numericStyle.BorderRight = BorderStyle.Thin; numericStyle.BorderTop = BorderStyle.Thin; numericStyle.Alignment = HorizontalAlignment.Center; numericStyle.VerticalAlignment = VerticalAlignment.Center; numericStyle.SetFont(font11); ISheet sheet = workbook.CreateSheet("Sheet0"); IRow rowHeader = sheet.CreateRow(0); rowHeader.Height = 20 * 30; for (int i = 0; i < cloumnlist.Count; i++) { var header = cloumnlist[i]; rowHeader.CreateCell(i); rowHeader.Cells[i].CellStyle = style1; rowHeader.Cells[i].SetCellValue(header); } response.Result = new MemoryStream(); workbook.Write(response.Result); workbook = null; response.Result.Close(); response.Result.Dispose(); response.Code = 200; response.Message = "获取成功"; } catch (Exception ex) { response.Code = 500; response.Message = ex.Message; } return response; } public async Task UploadExcel1(UploadExcelReq req) { using (var workbook = new XLWorkbook(req.file.OpenReadStream())) { string tableName = req.tableName; var wooksheet = workbook.Worksheet(1); IXLRows row = wooksheet.RowsUsed(); List rowCells = row.ToList(); IXLRow row1 = rowCells[0]; IXLCells cells = row1.CellsUsed(); var cols = new string[cells.Count()]; List listTableInfo = new List(); int k = 0; JsonObject json = new JsonObject(); List> listmap = new List>(); for (int i = 1; i < rowCells.Count; i++) { IXLRow rowi = rowCells[i]; IXLCells cellsi = rowi.CellsUsed(); Dictionary map = new Dictionary(); int g = 0; foreach (IXLCell cell in cellsi) { string head = cols[g]; map.Add(head, cell.Value); g++; } listmap.Add(map); } var count = wooksheet.RowCount(); _client.Insertable(listmap).AS(tableName).ExecuteCommand(); await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); return true; } } public bool UpdateTableData(UpdateTableReq req) { string tableName = req.TableName; int id = req.Id; var list = req.list; string sql = "update " + tableName + " set "; string sql1 = ""; for (int i = 0; i < list.Count; i++) { var map = list[i]; sql1 = sql1 + map["name"] + " = " + map["value"] + ","; } var sql2 = sql1.Substring(0,sql1.Length-1)+ " where 1=1 and \"Id\"="+id; _client.Ado.ExecuteCommand(sql + sql2); return true; } [HttpPost] public async Task AddUploadExcel(UploadExcelReq req) { using (var workbook = new XLWorkbook(req.file.OpenReadStream())) { string sql = $"delete from " + req.tableName; _client.Ado.ExecuteCommand(sql); string tableName = req.tableName; var wooksheet = workbook.Worksheet(1); IXLRows row = wooksheet.RowsUsed(); List rowCells = row.ToList(); IXLRow row1 = rowCells[0]; IXLCells cells = row1.CellsUsed(); var cols = new string[cells.Count()]; List listTableInfo = new List(); int k = 0; JsonObject json = new JsonObject(); List> listmap = new List>(); for (int i = 1; i < rowCells.Count; i++) { IXLRow rowi = rowCells[i]; IXLCells cellsi = rowi.CellsUsed(); Dictionary map = new Dictionary(); int g = 0; foreach (IXLCell cell in cellsi) { string head = cols[g]; map.Add(head, cell.Value); g++; } listmap.Add(map); } var count = wooksheet.RowCount(); _client.Insertable(listmap).AS(tableName).ExecuteCommand(); await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); return true; } } }