using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Bowin.Common.JSON; using Bowin.Common.Office; using Bowin.Common.ServiceToken.Permission; using Bowin.Common.WebModels; using YLShipBuildLandMap.Entity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Bowin.Common.Data; using System.Data; namespace YLShipBuildLandMap.Web.Controllers.Common { [Route("api/common/[controller]/[action]")] [Authorize] [ApiController] public class CommonController : ControllerBase { [HttpPost] public async Task ImportExcel([FromForm] string columns, [FromForm] int firstRow, [FromForm] int firstColumn) { try { Dictionary columnList = columns?.ToObject>(); var files = Request.Form.Files; if (files.Count == 0) { return Ok(new { success = false, msg = "没有上传的文件" }); } Stream stream = files[0].OpenReadStream(); var excel = new AsposeExcelHelper(); var sepeatColumn = excel.RepeatColumn(stream, firstRow); if (!string.IsNullOrEmpty(sepeatColumn)) { return Ok(new { success = false, msg = $"[{sepeatColumn}]列重复" }); } var dt = excel.ImportAsString(stream, firstRow, firstColumn); if (columnList.Keys.Where(x => !dt.Columns.Contains(x)).Any()) { var emptycolumns = columnList.Keys.Where(x => !dt.Columns.Contains(x)).ToArray(); return Ok(new { success = false, msg = $"[{string.Join(",", emptycolumns)}]列不存在导入文件" }); } if (columnList == null) { columnList = new Dictionary(); } columnList.Keys.ToList().ForEach(key => { dt.Columns[key].ColumnName = columnList[key]; }); return Ok(new { success = true, msg = "上传成功", item = dt }); } catch (Exception ex) { return Ok(new { success = false, msg = ex.Message }); throw; } } [HttpPost] public ResultMessage ImportErrorExport([FromBody] dynamic inputObj) { Dictionary columnList = inputObj.columns.ToObject>(); List> errorList = inputObj.items.ToObject>>(); int[] stringColumnList = inputObj.stringColumn?.ToObject(); var table = new DataTable(); foreach (var item in columnList) { table.Columns.Add(item.Value); } errorList.ForEach(data => { var row = table.NewRow(); foreach (var item in columnList) { if (data.ContainsKey(item.Key)) { row[item.Value] = data[item.Key]; } } table.Rows.Add(row); }); string[] liststring = columnList.Select(x => x.Value).ToArray(); AsposeExcelHelper excel = new AsposeExcelHelper(); var fileName = excel.ExportToFile(table, liststring, Configuration.Current.AppSettings.TemplatePhysicalPath, stringColumnList); return ResultMessage.Success(fileName); } } }