shp导出

DataMaintenance
zhangbin 2025-04-11 10:39:53 +08:00
parent 0fc176a678
commit 2ac7137473
3 changed files with 380 additions and 5 deletions

View File

@ -269,8 +269,7 @@ namespace OpenAuth.App.CodeTable
// 执行查询并获取结果
var viewColumns = db.Ado.SqlQuery<dynamic>(query, new { tableName = tableName });
return viewColumns;
}
}
}
#endregion
}

View File

@ -1,20 +1,32 @@
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using NetTopologySuite.Features;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using OpenAuth.App.Base.Tree;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.FormModule;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.ServiceApp.DataMaintenance.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Core;
using OpenAuth.Repository.Domain.DataMaintenance;
using Org.BouncyCastle.Asn1.Cms;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO.Compression;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
@ -169,8 +181,7 @@ namespace OpenAuth.App.ServiceApp.DataMaintenance
{
StringBuilder stringBuilder = new StringBuilder();
RefAsync<int> totalNumber = 0;
var query = db.Db.Queryable<object>().AS(tableDataReq.TableName);//没实体一样
// 构建过滤条件
var query = db.Db.Queryable<object>().AS(tableDataReq.TableName);
foreach (var filter in tableDataReq.Filter)
{
// 判断字段类型
@ -253,9 +264,277 @@ namespace OpenAuth.App.ServiceApp.DataMaintenance
}
#region 导出数据
public List<dynamic> GetTableAndViewColumnList(string tableName)
{
using (var db = UnitWork.CreateContext())
{
string query = $@"
SELECT
c.column_name,
c.data_type,
d.description
FROM
information_schema.columns c
LEFT JOIN
pg_catalog.pg_class t ON t.relname = c.table_name
LEFT JOIN
pg_catalog.pg_attribute a ON a.attnum > 0
AND a.attrelid = t.oid
AND a.attname = c.column_name
LEFT JOIN
pg_catalog.pg_namespace n ON n.oid = t.relnamespace
LEFT JOIN
pg_catalog.pg_description d ON d.objoid = a.attrelid
AND d.objsubid = a.attnum
WHERE
c.table_name = @tableName
AND c.table_schema = 'public';";
// 执行查询并获取结果
var viewColumns = db.Db.Ado.SqlQuery<dynamic>(query, new { tableName = tableName });
return viewColumns;
}
}
//查询所有数据
public async Task<List<dynamic>> GetDataAllList(TableDataReq tableDataReq)
{
using (var db = UnitWork.CreateContext())
{
StringBuilder stringBuilder = new StringBuilder();
var query = db.Db.Queryable<object>().AS(tableDataReq.TableName);
foreach (var filter in tableDataReq.Filter)
{
// 判断字段类型
if (filter.Type == "int")
{
query.Where(BuildIntCondition(filter.Field, filter.Operator, filter.Value));
}
else
{
query.Where(BuildStringCondition(filter.Field, filter.Operator, filter.Value));
}
}
var fields = string.Join(",", tableDataReq.Field.Select(f => $"\"{f}\""));
var dataList = await query.Select<dynamic>(fields).ToListAsync();
return dataList;
}
}
//导出Excel
public async Task<Response<MemoryStream>> ListToExcel(TableDataReq tableDataReq, List<ModuleColumn> headers)
{
Response<MemoryStream> response = new Response<MemoryStream>();
try
{
var list = await GetDataAllList(tableDataReq);
HSSFWorkbook workbook = new HSSFWorkbook();
#region 内容样式
IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
//font1.Boldweight = short.MaxValue;//字体加粗
font1.FontHeightInPoints = 12; //字体大小
ICellStyle style = workbook.CreateCellStyle(); //创建样式对象
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
style.SetFont(font1); //将字体样式赋给样式对象
style.WrapText = true;
#endregion
#region 标题样式
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 = NPOI.SS.UserModel.HorizontalAlignment.Center;
style1.VerticalAlignment = VerticalAlignment.Center;
style1.SetFont(font); //将字体样式赋给样式对象
#endregion
#region 创建表头
int m = list.Count / 60000 + 1;
for (int k = 0; k < m; k++)
{
ISheet sheet = workbook.CreateSheet("Sheet" + k.ToString());
IRow rowHeader = sheet.CreateRow(0);
rowHeader.Height = 20 * 30;
for (int i = 0; i < tableDataReq.Field.Count; i++)
{
rowHeader.CreateCell(i);
rowHeader.Cells[i].CellStyle = style1;
var va = headers.Where(r => r.key == tableDataReq.Field[i].ToString()).FirstOrDefault().value;
rowHeader.Cells[i].SetCellValue(va);
sheet.SetColumnWidth(i, 20 * 350);
}
#endregion
#region 填充数据
var val = (k + 1) * 60000;
var num = 60000;
if (val > list.Count())
{
num = list.Count - k * 60000;
}
for (int i = 0; i < num; i++) //循环数据
{
var item = list[k * 60000 + i]; //获取数据
IRow dataRow = sheet.CreateRow(i + 1); //创建行
for (int j = 0; j < tableDataReq.Field.Count; j++) //循环表头
{
//数据处理
var objValue = "";
var fieldKey = tableDataReq.Field[j].ToString();
if (item is ExpandoObject expandoItem)
{
var dictItem = (IDictionary<string, object>)expandoItem;
if (dictItem.ContainsKey(fieldKey))
{
objValue = dictItem[fieldKey]?.ToString();
}
}
//创建单元格
dataRow.CreateCell(j);
dataRow.Cells[j].CellStyle = style; //添加单元格样式
if (objValue != null && !string.IsNullOrEmpty(objValue.ToString()))
{
dataRow.Cells[j].SetCellValue(objValue.ToString()); //填充Excel单元格
}
else
{
dataRow.Cells[j].SetCellValue(""); //填充Excel单元格
}
}
}
}
#endregion
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;
}
//导出shp文件
/// <summary>
/// 导出shp文件
/// </summary>
/// <param name="req"></param>
/// <param name="shpFilePath"></param>
/// <param name="shpFilePathzip"></param>
/// <exception cref="Exception"></exception>
public async void ExportShapefile(TableDataReq tableDataReq, string shpFilePath, string shpFilePathzip, List<ModuleColumn> headers)
{
var data = await GetDataAllList(tableDataReq);
if (data == null || data.Count == 0)
{
throw new Exception("暂无数据");
}
List<IFeature> features = new List<IFeature>();
foreach (var row in data)
{
var geometry = ParseGeometry(row.geom.ToString());
if (geometry == null)
{
throw new Exception("数据不可用");
}
AttributesTable attributes = new AttributesTable();
IFeature feature;
for (int i = 0; i < tableDataReq.Field.Count; i++)
{
var va = headers.Where(r => r.key == tableDataReq.Field[i].ToString()).FirstOrDefault().value;
// 访问动态属性
var fieldName = tableDataReq.Field[i].ToString();
var fieldValue = row.GetType().GetProperty(fieldName)?.GetValue(row, null);
if (row is ExpandoObject expandoItem)
{
var dictItem = (IDictionary<string, object>)expandoItem;
if (dictItem.ContainsKey(fieldName))
{
attributes.Add(va, dictItem[fieldName]?.ToString());
}
}
}
feature = new Feature(geometry, attributes);
features.Add(feature);
}
if (features.Count == 0)
{
throw new Exception("数据不可用");
}
// 导出 SHP 文件及其关联文件
ExportToShapefileFour(shpFilePath, features);
// 将文件打包成 ZIP
CreateZipFromShapefiles(shpFilePath, shpFilePathzip);
}
public Geometry ParseGeometry(string wkt)
{
if (string.IsNullOrEmpty(wkt))
{
return null;
}
var reader = new WKTReader();
return reader.Read(wkt);
}
public void ExportToShapefileFour(string shpPath, List<IFeature> features)
{
string prjStr =
@"GEOGCS[""GCS_China_Geodetic_Coordinate_System_2000"",DATUM[""D_China_2000"",SPHEROID[""CGCS2000"",6378137.0,298.257222101]],PRIMEM[""Greenwich"",0.0],UNIT[""Degree"",0.0174532925199433]]";
var cpgPath = System.IO.Path.ChangeExtension(shpPath, "prj");
System.IO.File.WriteAllText(cpgPath, prjStr, Encoding.UTF8);
NetTopologySuite.IO.Esri.Shapefile.WriteAllFeatures(features, shpPath, encoding: Encoding.UTF8);
}
public void CreateZipFromShapefiles(string shpPath, string zipPath)
{
var files = new List<string>
{
System.IO.Path.ChangeExtension(shpPath, "cpg"),
shpPath,
System.IO.Path.ChangeExtension(shpPath, "shx"),
System.IO.Path.ChangeExtension(shpPath, "dbf"),
System.IO.Path.ChangeExtension(shpPath, "prj")
};
using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
foreach (var file in files)
{
if (System.IO.File.Exists(file))
{
zipArchive.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
}
}
}
}
#endregion
}
}

View File

@ -1,12 +1,18 @@
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using OpenAuth.App;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.FormModule;
using OpenAuth.App.FormScheme.Request;
using OpenAuth.App.ServiceApp.DataMaintenance;
using OpenAuth.App.ServiceApp.DataMaintenance.Request;
using OpenAuth.Repository.Domain.DataMaintenance;
using OpenAuth.WebApi.Model.CustomAttribute;
using System.Data;
using OpenAuth.App.CodeTable;
namespace OpenAuth.WebApi.Controllers.ServiceControllers.DataMaintenance
{
@ -93,5 +99,96 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers.DataMaintenance
}
return result;
}
/// <summary>
/// 获取数据库表及视图字段
/// </summary>
/// <param name="dbCode"></param>
/// <param name="tableName"></param>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public Response<List<dynamic>> GetTableAndViewColumnList( string tableName)
{
var result = new Response<List<dynamic>>();
try
{
result.Result = _app.GetTableAndViewColumnList( tableName);
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.Message;
}
return result;
}
#region 获取导出数据
/// <summary>
/// 获取导出数据
/// </summary>
/// <param name="mid">功能id</param>
/// <param name="id">id数据</param>
/// <param name="query">查询参数</param>
/// <param name="code">编号</param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Export(TableDataReq tableDataReq)
{
//查询表头
var tableHeader = _app.GetTableAndViewColumnList(tableDataReq.TableName);
List<ModuleColumn> cl = new List<ModuleColumn>();
foreach (var item in tableHeader)
{
ModuleColumn c = new ModuleColumn();
c.key = item.column_name.ToString();
c.value = item.description.ToString();
cl.Add(c);
}
var excelRes =await _app.ListToExcel(tableDataReq, cl);
if (excelRes.Code == 200)
{
return File(excelRes.Result.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"数据导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
}
else
{
}
return Ok();
}
/// <summary>
/// 导出案件shp文件
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public IActionResult ExportShapefile(TableDataReq tableDataReq)
{
try
{
var tableHeader = _app.GetTableAndViewColumnList(tableDataReq.TableName);
List<ModuleColumn> cl = new List<ModuleColumn>();
foreach (var item in tableHeader)
{
ModuleColumn c = new ModuleColumn();
c.key = item.column_name.ToString();
c.value = item.description.ToString();
cl.Add(c);
}
string shpFilePath = Path.Combine(Path.GetTempPath(), $"数据信息{DateTime.Now:yyyyMMddHHmmss}.shp");
string shpFilePathzip = Path.Combine(Path.GetTempPath(), $"数据信息{DateTime.Now:yyyyMMddHHmmss}.zip");
_app.ExportShapefile(tableDataReq, shpFilePath, shpFilePathzip, cl);
byte[] fileBytes = System.IO.File.ReadAllBytes(shpFilePathzip);
return File(fileBytes, "application/octet-stream", $"数据信息{DateTime.Now:yyyyMMddHHmmss}.zip");
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
#endregion
}
}