You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1317 lines
56 KiB

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using SqlSugar;
using Tiobon.Core.Common;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Model.Models;
namespace Tiobon.Core.DataAccess;
/// <summary>
/// 报表辅助类
/// </summary>
public static class ReportHelper
{
#region 文件下载
/// <summary>
/// 生成文件,并通知用户下载(IQueryable)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="modelName">导出模块名称(JobSetting.xxx)</param>
/// <param name="exportFields"></param>
/// <param name="exportFieldsWidth"></param>
/// <param name="user"></param>
/// <param name="sort"></param>
/// <param name="headText"></param>
/// <param name="totalText"></param>
/// <param name="isNeedItemNo"></param>
public static async Task<long> SendFile<T>(IQueryable<T> list, string modelName, List<string> exportFields, List<int> exportFieldsWidth, string sort = null, string headText = "", string totalText = "", bool isNeedItemNo = false) where T : class
{
if (list == null)
throw new Exception("生成文件失败");
//生成文件至文件服务器
var fid = SnowFlakeSingle.Instance.NextId();
var path = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}export{Path.DirectorySeparatorChar}{fid}{Path.DirectorySeparatorChar}"}";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var fname = $"{modelName}.xlsx";
list = string.IsNullOrEmpty(sort) ? list : list.OrderBy(sort);
list.IntoFileFromLinqExcel(path + fname, ",", exportFields, exportFieldsWidth, headText, totalText, isNeedItemNo);
using var _context = ContextFactory.CreateContext();
Ghre_Attachment fileAttachment = new Ghre_Attachment();
fileAttachment.Id = fid;
fileAttachment.AttachFileName = fname;
fileAttachment.CreateBy = App.User.ID;
fileAttachment.CreateTime = DateTime.Now;
fileAttachment.AttachmentName = fname;
fileAttachment.AttachFileExtension = "xlsx";
fileAttachment.AttachFileSize = 0;
fileAttachment.PhysicsPath = $"/files/export/{fid}/" + fname;
fileAttachment.AttachmentType = "xlsx";
await _context.Ghre_Attachment.AddAsync(fileAttachment);
await _context.SaveChangesAsync();
return fid;
}
public static async Task<long> SendFile(DataTable list, string modelName, Dictionary<string, string> fieldDescs, List<int> exportFieldsWidth, string sort = null, string headText = "", string totalText = "", bool isNeedItemNo = false)
{
if (list == null)
throw new Exception("生成文件失败");
//生成文件至文件服务器
var fid = SnowFlakeSingle.Instance.NextId();
var path = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}export{Path.DirectorySeparatorChar}{fid}{Path.DirectorySeparatorChar}"}";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var fname = $"{modelName}.xlsx";
list.IntoFileFromLinqExcel(path + fname, ",", fieldDescs, exportFieldsWidth, headText, totalText, isNeedItemNo);
using var _context = ContextFactory.CreateContext();
Ghre_Attachment fileAttachment = new Ghre_Attachment();
fileAttachment.Id = fid;
fileAttachment.AttachFileName = fname;
fileAttachment.CreateBy = App.User.ID;
fileAttachment.CreateTime = DateTime.Now;
fileAttachment.AttachmentName = fname;
fileAttachment.AttachFileExtension = "xlsx";
fileAttachment.AttachFileSize = 0;
fileAttachment.PhysicsPath = $"/files/export/{fid}/" + fname;
fileAttachment.AttachmentType = "xlsx";
await _context.Ghre_Attachment.AddAsync(fileAttachment);
await _context.SaveChangesAsync();
return fid;
}
#endregion
public static async Task<long> ImportTemplate(ISqlSugarClient Db, List<QueryExportColumn> tableColumn, DataTable dt, string menuName)
{
//生成表格
try
{
//生成文件至文件服务器
var fid = SnowFlakeSingle.Instance.NextId();
var filepath = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{fid}{Path.DirectorySeparatorChar}"}";
if (!Directory.Exists(filepath))
Directory.CreateDirectory(filepath);
var fname = $"{menuName}.xlsx";
IWorkbook fileWorkbook;
bool IsHSSF = true;
if (Path.GetExtension(filepath) == ".xls")
{
IsHSSF = true;
fileWorkbook = new HSSFWorkbook();
}
else
{
IsHSSF = false;
fileWorkbook = new XSSFWorkbook();
}
int index = 0;
//创建Sheet;
ISheet sheet = fileWorkbook.CreateSheet("导入数据");
ISheet sheet2 = fileWorkbook.CreateSheet("下拉数据");
//隐藏下拉数据Sheet
//fileWorkbook.SetSheetHidden(fileWorkbook.GetSheetIndex("下拉数据"), SheetState.Hidden);
IRow erow_1 = sheet.CreateRow(0); //ID行
IRow erow_2 = sheet.CreateRow(1); //文本行
erow_1.CreateCell(0).SetCellValue("ExcelNums");
erow_2.CreateCell(0).SetCellValue("序号");
//必填颜色
var CellRed = fileWorkbook.CreateCellStyle(); // 创建单元格样式
IFont Font = fileWorkbook.CreateFont(); // 创建字体
Font.Color = IndexedColors.Red.Index; // 选择字体颜色
CellRed.SetFont(Font); // 把字体赋给样式
erow_2.GetCell(0).CellStyle = CellRed;
//文本类型
ICellStyle cellString = fileWorkbook.CreateCellStyle();
IDataFormat cellFormat = fileWorkbook.CreateDataFormat();
cellString.DataFormat = cellFormat.GetFormat("@");
//下拉数据列ID
int listColIndex = 0;
int ColNums = 0;
foreach (var drow in tableColumn)
{
int SortNum = Convert.ToInt32(drow.sortNum);
ICell cell = erow_1.CreateCell(SortNum);
ICell cel2 = erow_2.CreateCell(SortNum);
string field = drow.field;
;
string label = drow.label;
// 批注
string commentText = string.Empty;
try
{
commentText = drow.commentText;
}
catch (Exception)
{
}
cell.SetCellValue(field);
cel2.SetCellValue(label);
// 设置批注
if (!string.IsNullOrEmpty(commentText))
{
cel2.CellComment = GetComment(sheet, null, ColNums, commentText);
}
//是否必填
if (drow.required == "true")
{
cel2.CellStyle = CellRed;
}
string dataSource = drow.dataSource;
//是否下拉
if (!string.IsNullOrEmpty(dataSource)
&& !dataSource.StartsWith("OrgTreeWith")
&& !dataSource.StartsWith("StaffWith")
)
{
List<DataSourceList> dataSourceLists = GetDataSourceLists(Db, field, dataSource);
//下拉数据行ID
int listRowIndex = 1;
//写入下拉值区域
IRow rowTitle = sheet2.GetRow(0);
if (rowTitle == null)
rowTitle = sheet2.CreateRow(0);
rowTitle.CreateCell(listColIndex).SetCellValue(label);
foreach (var data in dataSourceLists)//将下拉列表中的数据循环赋给sheet页
{
IRow row = sheet2.GetRow(listRowIndex);
if (row == null)
row = sheet2.CreateRow(listRowIndex);
listRowIndex = listRowIndex + 1;
row.CreateCell(listColIndex).SetCellValue(data.name);
}
// 定义一个名称,指向刚才创建的下拉项的区域:
var rangeName = field + "Range";
IName range = fileWorkbook.CreateName();
string ABC = Other.Num2ABCletter((listColIndex + 1));
//range.RefersToFormula = "下拉数据" + "!$"+ ABC + "$2:$"+ ABC + "$" + (listRowIndex == 0 ? 2 : listRowIndex);
//Excel 正常引用
string a1 = "下拉数据" + "!$" + ABC + "$2:$" + ABC + "$" + (listRowIndex == 0 ? 2 : listRowIndex);
// Excel R1C1引用样式
string a2 = "下拉数据" + "!$R2C" + listColIndex.ToString() + ":R" + listRowIndex.ToString() + "C" + listColIndex.ToString();
listColIndex = listColIndex + 1;
range.RefersToFormula = a1;
range.NameName = rangeName;
//-----------------分割线以上是用来创建一个sheet页赋值,然后将sheet页中的内容定义成一个名称,后面用来当作数组传入方法的过程
CellRangeAddressList cellRegions = new CellRangeAddressList(1, 65535, SortNum, SortNum);//
DVConstraint constraint = DVConstraint.CreateFormulaListConstraint(rangeName);
//HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint);
//IDataValidationConstraint constraint;
IDataValidation dataValidate;
if (Path.GetExtension(filepath) == ".xls")
{
constraint = DVConstraint.CreateFormulaListConstraint(rangeName);
dataValidate = new HSSFDataValidation(cellRegions, constraint);
}
else
{
CT_DataValidation cdv = new CT_DataValidation();
cdv.allowBlank = true;
//constraint = CT_DataValidation
dataValidate = new XSSFDataValidation(cellRegions, cdv);
}
// 多选 ,自行输入不报错
if (drow.elementType.ToString().LastIndexOf("multiple") == -1)
{
dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。");
dataValidate.ShowPromptBox = true;
}
else
{
dataValidate.ShowErrorBox = false;
}
sheet.AddValidationData(dataValidate);
}
//是否文本格式
if (drow.dataType != "int"
&& drow.dataType != "decimal"
&& drow.dataType != "number"
)
{
sheet.SetDefaultColumnStyle(ColNums, cellString);
}
ColNums = ColNums + 1;
}
erow_1.HeightInPoints = 1;
// 如果导出模板存在默认数据
//if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 2);
ICell cell = row1.CreateCell(0);
cell.SetCellValue(i + 1);
for (int j = 1; j <= tableColumn.Count; j++)
{
cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][tableColumn[j - 1].field].ToString());
}
}
// Sheet 更改列为自适应宽度
for (int col = 0; col <= ColNums; col++)
{
try
{
sheet.AutoSizeColumn(col);//自适应宽度,但是其实还是比实际文本要宽
var columnWidth = sheet.GetColumnWidth(col) / 256;//获取当前列宽度
for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
{
IRow row = sheet.GetRow(rowIndex);
ICell cell = row.GetCell(col);
int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度
columnWidth = columnWidth < contextLength ? contextLength : columnWidth;
}
sheet.SetColumnWidth(col, columnWidth * 256);//
}
catch (Exception)
{
}
}
// Sheet2 更改列为自适应宽度
//if (listColIndex > 0)
//{
// for (int col = 0; col <= listColIndex - 1; col++)
// {
// sheet2.AutoSizeColumn(col);//自适应宽度,但是其实还是比实际文本要宽
// int columnWidth = sheet2.GetColumnWidth(col) / 256;//获取当前列宽度
// for (int rowIndex = 1; rowIndex <= sheet2.LastRowNum; rowIndex++)
// {
// IRow row = sheet2.GetRow(rowIndex);
// ICell cell = row.GetCell(col);
// int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度
// columnWidth = columnWidth < contextLength ? contextLength : columnWidth;
// }
// sheet2.SetColumnWidth(col, columnWidth * 256);//
// }
//}
//转为字节数组
MemoryStream stream = new MemoryStream();
fileWorkbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(filepath + fname, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}
catch (Exception ex)
{
}
return default(long);
}
/// <summary>
/// Excel字段下拉
/// </summary>
public class DataSourceList
{
public string field { get; set; }
public string id { get; set; }
public string no { get; set; }
public string name { get; set; }
} /// <summary>
/// 设置Excel批注
/// </summary>
/// <param name="sheet"> sheet</param>
/// <param name="comment"> comment </param>
/// <param name="cellnum"> 列 </param>
/// <param name="text">文本</param>
/// <returns></returns>
private static IComment GetComment(ISheet sheet, IComment comment, int cellnum, string text)
{
IWorkbook workbook = sheet.Workbook;
bool exportXlsx = workbook is XSSFWorkbook;
if (comment == null)
{
IDrawing draw = sheet.CreateDrawingPatriarch();
IClientAnchor clientAnchor = null;
if (exportXlsx)
{
clientAnchor = new XSSFClientAnchor(0, 0, 0, 0, cellnum, 0, cellnum + 2, 6);
}
else
{
clientAnchor = new HSSFClientAnchor(0, 0, 0, 0, cellnum, 0, cellnum + 2, 6);
}
comment = draw.CreateCellComment(clientAnchor);
}
IRichTextString richText = null;
if (exportXlsx)
{
richText = new XSSFRichTextString(string.Format("{0}", text));
}
else
{
richText = new HSSFRichTextString(string.Format("{0}", text));
}
//richText.ApplyFont(GetDefaultFont(workbook, true));// 设置批注中文本的字体
comment.String = richText;
comment.Visible = false;
comment.Author = "Tiobon";
return comment;
}
/// <summary>
/// 获取数据下拉
/// </summary>
/// <param name="dataSource"></param>
/// <returns></returns>
public static List<DataSourceList> GetDataSourceLists(ISqlSugarClient Db, string field, string dataSource)
{
List<DataSourceList> dataSourceList = new List<DataSourceList>();
try
{
////Dept
//if (dataSource.StartsWith("OrgTreeWith"))
//{
//}
////Staff
//else if (dataSource.StartsWith("StaffWith"))
//{
//}
//else
{
string listSQL = string.Format(@"exec[dbo].[PRI_ListValue] '{0}','GetEnableList','',1,63,'',9999,1,2", dataSource);
DataSet listds = Db.Ado.GetDataSetAll(listSQL);
if (listds.Tables.Count > 3)
{
DataTable listdt = new DataTable();
listdt = listds.Tables[2];
foreach (DataRow row in listdt.Rows)
{
DataSourceList _dataSource = new DataSourceList();
_dataSource.field = field;
try
{
_dataSource.id = row["value"].ToString();
_dataSource.name = row["label"].ToString();
}
catch (Exception)
{
_dataSource.id = row[0].ToString();
_dataSource.name = row[1].ToString();
try
{
_dataSource.name = _dataSource.name + " " + row[2].ToString();
}
catch (Exception)
{
}
}
dataSourceList.Add(_dataSource);
}
}
}
}
catch (Exception)
{
}
return dataSourceList;
}
/// <summary>
///
/// </summary>
/// <param name="sheet"></param>
/// <param name="sql">需要写入的查询的SQL</param>
/// <param name="rows">开始行</param>
/// <param name="cols">开始列</param>
/// <returns></returns>
public static bool InsertExcelList(ISqlSugarClient Db, ISheet sheet, string sql)
{
bool IsBool = false;
DataSet ds = Db.Ado.GetDataSetAll(sql);
//写入下拉值区域
int cols = 0;
foreach (DataTable dt in ds.Tables)
{
int col = 0;
//表头
IRow row = sheet.GetRow(0);
if (row == null)
row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i + cols);
cell.SetCellValue(dt.Columns[i].ColumnName);
col++;
}
//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.GetRow(i + 1);
if (row1 == null)
row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j + cols);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
cols = cols + col + 1;
}
return IsBool;
}
/// <summary>
/// 是否隐藏首行
/// </summary>
public static bool IsHideTopRow = false;
/// <summary>
/// 读取Excel写入临时表,逻辑在存储过程里写
/// </summary>
/// <returns></returns>
public static async Task<string> ExcelToDataTable(ISqlSugarClient Db, string FilePath, string menuName, int LangID, int UserID, string doType = null, string procName = null)
{
string result = string.Empty;
int ErrorNum = 0;
int SuccessNum = 0;
DataTable mydt = GetDataTable(FilePath, 0, null);
if (mydt.Columns["Comments"] == null)
{
mydt.Columns.Add("Comments", typeof(string));
}
mydt.Rows[0]["Comments"] = "提示信息";
//从第二行开始读取
int FirstI = 1;
IsHideTopRow = true;
//创建GUID;
string guidN = Guid.NewGuid().ToString("N");
DataTable edt = new DataTable();
edt.Columns.Add("ExcelNums", typeof(int));//
edt.Columns.Add("GID", typeof(string));//
edt.Columns.Add("LangID", typeof(int));//
edt.Columns.Add("UserID", typeof(int));//
edt.Columns.Add("DoType", typeof(string));//
edt.Columns.Add("ProcName", typeof(string));//
edt.Columns.Add("MenuName", typeof(string));//
edt.Columns.Add("JsonColumns", typeof(string));//
// 获取对应的字段设定
DataSet ds = new DataSet();
if (menuName != "F_SchedulePeriodSetup")
ds = await GetTableColumn(Db, LangID, UserID, menuName, null);
DataTable tableColumn = ds.Tables.Count > 0 ? ds.Tables[0] : new DataTable();
List<DataSourceList> dataSourceLists = new List<DataSourceList>();
foreach (DataRow dr in tableColumn.Rows)
{
// 验证导入列是否一致
if (!mydt.Columns.Contains(dr["field"].ToString()) && doType != "Update")
{
throw new Exception("导入模板不匹配或模板字段已更新,请重新下载导入模板");
}
string dataSource = dr["dataSource"].ToString();
string field = dr["field"].ToString();
if (!string.IsNullOrEmpty(dataSource))
{
List<DataSourceList> dataSourceList = GetDataSourceLists(Db, field, dataSource);
dataSourceLists.AddRange(dataSourceList);
}
}
int AllNums = 0;
// 判断是否为流程,流程直接返回对应信息
string IsFlow = "N";
StringBuilder jsonListBuilder = new StringBuilder();
jsonListBuilder.Append("[");
//循环读取的Excel行
for (int i = FirstI; i < mydt.Rows.Count; i++)
{
AllNums++;
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
string errorMsg = string.Empty;
//// 遍历列
foreach (DataColumn dc in mydt.Columns)
{
if (dc.ColumnName != "Process" && dc.ColumnName != "Comments" && dc.ColumnName != "" && dc.ColumnName != "ExcelNums")
{
string value = mydt.Rows[i][dc.ColumnName].ToString();
string value_label = value;
//判断对应的字段设定
DataRow[] rows = ds.Tables.Count > 0 ? tableColumn.Select(" field = '" + dc.ColumnName + "' ") : null;
if (rows != null && rows.Length > 0)
{
DataRow fieldRow = rows[0];
// 必填字段为空
if (fieldRow["required"].ToString() == "true" && string.IsNullOrEmpty(value))
{
errorMsg = errorMsg + fieldRow["label"].ToString() + "不能为空;";
}
string dataSource = fieldRow["dataSource"].ToString();
//下拉数据反读值
//if (!string.IsNullOrEmpty(dataSource) && !string.IsNullOrEmpty(value)
// // 默认值处理
// && !(value == "*" && menuName.StartsWith("F_StaffChange")))
//{
// //// Dept
// if (dataSource.StartsWith("OrgTreeWith"))
// {
// string DeptID = string.Empty;
// // 部门需要一级一级写入,不判断父级层级
// if (menuName != "F_AllDept" && menuName != "F_Dept")
// {
// try
// {
// //验证部门编号填写是否错误
// string DeptTest = string.Format(@"select STUFF((select ','+value
// from dbo.Fs1_GHR30_SplitString('{0}',',')
// where value != '' and value not in (select DeptNo from Ghro_Dept where ISEnable=1)
// for XML path(''),type).value('.','nvarchar(max)'),1,1,'');",
// value);
// DeptTest = DataAccess.SelectSingleValueNotKey("SqlGhr30" + "Demo", DeptTest).ToString();
// if (!String.IsNullOrEmpty(DeptTest))
// {
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值(" + DeptTest + ")错误;";
// }
// else
// {
// string deptExists = string.Format(@"select stuff((select ',' + CONVERT(nvarchar(10),DeptID)
// from Ghro_Dept
// where IsEnable=1
// and DeptNo in (select value from dbo.Fs1_GHR30_SplitString('{0}',','))
// for XML path(''),type).value('.','nvarchar(max)'),1,1,'');",
// value);
// DeptID = DataAccess.SelectSingleValueNotKey("SqlGhr30" + "Demo", deptExists).ToString();
// value = DeptID;
// //if (String.IsNullOrEmpty(value))
// // errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// }
// }
// catch (Exception)
// {
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// }
// }
// }
// //// Staff
// else if (dataSource.StartsWith("StaffWith"))
// {
// string StaffID = string.Empty;
// try
// {
// //验证工号填写是否错误
// string StaffTest = string.Format(@"select STUFF((select ','+value
// from dbo.Fs1_GHR30_SplitString('{0}',',')
// where value != '' and value not in (select StaffNo from Ghra_Staff where ISEnable=1)
// for XML path(''),type).value('.','nvarchar(max)'),1,1,'');",
// value);
// StaffTest = DataAccess.SelectSingleValueNotKey("SqlGhr30" + "Demo", StaffTest).ToString();
// if (!String.IsNullOrEmpty(StaffTest))
// {
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值(" + StaffTest + ")错误;";
// }
// else
// {
// string staffExists = string.Format(@"select stuff((select ',' + CONVERT(nvarchar(10),StaffID)
// from Ghra_Staff
// where IsEnable=1
// and StaffNo in (select value from dbo.Fs1_GHR30_SplitString('{0}',','))
// for XML path(''),type).value('.','nvarchar(max)'),1,1,'');",
// value);
// StaffID = DataAccess.SelectSingleValueNotKey("SqlGhr30" + "Demo", staffExists).ToString();
// value = StaffID;
// if (String.IsNullOrEmpty(value))
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// }
// }
// catch (Exception)
// {
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// }
// }
// else
// {
// try
// {
// // 多选
// if (fieldRow["elementType"].ToString().LastIndexOf("multiple") == -1)
// {
// DataSourceList nList = dataSourceLists.First(t => t.name == value && t.field == dc.ColumnName);
// if (nList != null)
// {
// if (String.IsNullOrEmpty(nList.id))
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// else
// value = nList.id;
// }
// }
// else
// {
// string errorValue = string.Empty;
// string newValue = "[";
// foreach (var sp in value.Split(','))
// {
// DataSourceList nList = dataSourceLists.First(t => t.name == sp && t.field == dc.ColumnName);
// if (nList != null)
// {
// if (String.IsNullOrEmpty(nList.id))
// errorValue = errorValue + fieldRow["label"].ToString() + ",";
// else
// newValue = newValue + "\"" + nList.id + "\",";
// }
// else
// {
// errorValue = errorValue + fieldRow["label"].ToString() + ",";
// }
// }
// if (!string.IsNullOrEmpty(errorValue))
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值(" + errorValue + ")错误;";
// else
// value = newValue.TrimEnd(',') + "]";
// }
// }
// catch (Exception)
// {
// errorMsg = errorMsg + fieldRow["label"].ToString() + "输入值错误;";
// value = "0";
// }
// }
//}
// 部门需要一级一级写入,不判断父级层级
if (menuName != "F_AllDept" && menuName != "F_Dept"
&& fieldRow["field"].ToString().IndexOf("ParentDeptID") > 0
&& !(value == "*" && menuName.StartsWith("F_StaffChange"))
)
{
// 是否输入整型
if (fieldRow["dataType"].ToString() == "int" && !string.IsNullOrEmpty(value))
{
int nums1;
if (!int.TryParse(value, out nums1))
errorMsg = errorMsg + fieldRow["label"].ToString() + "需为整数;";
}
// 是否输入数值
if ((fieldRow["dataType"].ToString() == "decimal" || fieldRow["dataType"].ToString() == "number")
&& !string.IsNullOrEmpty(value))
{
double nums2;
if (!double.TryParse(value, out nums2))
errorMsg = errorMsg + fieldRow["label"].ToString() + "需为数值;";
}
}
// 是否输入日期
if (fieldRow["dataType"].ToString().StartsWith("date")
&& !(value == "*" && menuName.StartsWith("F_StaffChange"))
)
{
if (!string.IsNullOrEmpty(value))
{
try
{
DateTime date1;
if (!DateTime.TryParse(value, out date1))
errorMsg = errorMsg + fieldRow["label"].ToString() + "需为日期格式;";
else if (fieldRow["dataType"].ToString() == "date")
{
value = date1.ToString("yyyy-MM-dd");
}
}
catch (Exception)
{
errorMsg = errorMsg + fieldRow["label"].ToString() + "(" + value + ")需为日期格式;";
}
}
else
{
}
}
if (fieldRow["elementType"].ToString().LastIndexOf("multiple") == -1)
{
jsonBuilder.AppendFormat("\"{0}\":\"{1}\",",
dc.ColumnName, value.Replace('"', '‘').Replace("'", "‘").Trim());
}
else
{
jsonBuilder.AppendFormat("\"{0}\":{1},",
dc.ColumnName, string.IsNullOrEmpty(value.Trim()) ? "null" : value.Trim());
}
}
else
{
jsonBuilder.AppendFormat("\"{0}\":\"{1}\",",
dc.ColumnName, value.Replace('"', '‘').Replace("'", "‘").Trim());
}
// ESS申请 下拉返回label 值
if (IsFlow == "Y")
{
jsonBuilder.AppendFormat("\"{0}\":\"{1}\",",
dc.ColumnName + "_Label", value_label.Trim());
}
}
}
if (jsonBuilder.Length > 1)
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("}");
//判断 是否有错误
if (!string.IsNullOrEmpty(errorMsg))
{
mydt.Rows[i]["Comments"] = errorMsg;
ErrorNum++;
}
else
{
DataRow ndr = edt.NewRow();
ndr["ExcelNums"] = mydt.Rows[i]["ExcelNums"].ToString();
ndr["GID"] = guidN;
ndr["LangID"] = LangID;
ndr["UserID"] = UserID;
ndr["DoType"] = doType;
ndr["ProcName"] = procName;
ndr["MenuName"] = menuName;
ndr["JsonColumns"] = jsonBuilder.ToString();
edt.Rows.Add(ndr);
// 写入正确的json
jsonListBuilder.Append(jsonBuilder);
jsonListBuilder.Append(",");
}
}
if (jsonListBuilder.Length > 1)
jsonListBuilder.Remove(jsonListBuilder.Length - 1, 1);
jsonListBuilder.Append("]");
// 写入Excel待读取
string createTempSQL = "ExcelNums int,GID nvarchar(100),LangID int,UserID int,DoType nvarchar(200),ProcName nvarchar(200),MenuName nvarchar(200),JsonColumns nvarchar(max)";
string updateSQL = @"insert into [dbo].[Ghrs_ExcelImportWait]
([GID],[LangID],[UserID],[DoType], [ProcName], [MenuName], [JsonColumns],[SortNo])
select[GID],[LangID],[UserID],[DoType], [ProcName],[MenuName] ,[JsonColumns],ExcelNums
from #CTemplateTable";
Other.BulkUpdateData("SqlGhr30" + "Demo", edt, createTempSQL, updateSQL);
//Db.Ado.GetDataTable("SqlGhr30" + "Demo", edt, createTempSQL, updateSQL);
string EssResult = string.Empty;
//调用存储过程
// GHR 导入
if (IsFlow == "N")
{
string ReadSQL = string.Format(@"exec[dbo].[PT_GHR30_ReadExcelData] '{0}',{1},{2} ", guidN, LangID, UserID);
await Db.Ado.ExecuteCommandAsync("SqlGhr30" + "Demo", ReadSQL);
string resultSQL = string.Format(@"select SortNo,ErrorMsg,WarningMsg,SuccessMsg
from Ghrs_ExcelImportResult
where GID = '{0}'
and ISNULL(ErrorMsg,'') != '' ", guidN);
DataTable resultDt = await Db.Ado.GetDataTableAsync(resultSQL);
//写入错误信息
foreach (DataRow resultDR in resultDt.Rows)
{
string SortNo = resultDR["SortNo"].ToString();
string ErrorMsg = "";
ErrorMsg = resultDR["ErrorMsg"].ToString();
mydt.Select(@"ExcelNums = '" + SortNo + "'")[0]["Comments"] = ErrorMsg;
ErrorNum++;
}
}
else
{
string ReadSQL = string.Format(@"exec[dbo].[PT_GHR30_EssFlowReadExcelData] '{0}',{1},{2} ", guidN, LangID, UserID);
DataTable resultDt = await Db.Ado.GetDataTableAsync(ReadSQL);
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
foreach (DataRow resultDR in resultDt.Rows)
{
jsonBuilder.Append(resultDR["ResultJson"].ToString() + ",");
string SortNo = resultDR["SortNo"].ToString();
string ErrorMsg = "";
ErrorMsg = resultDR["FlowApplyDetailInfo"].ToString();
if (ErrorMsg != String.Empty)
{
ErrorNum++;
mydt.Select(@"ExcelNums = '" + SortNo + "'")[0]["Comments"] = ErrorMsg;
}
}
if (jsonBuilder.Length > 1)
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
EssResult = jsonBuilder.ToString();
}
SuccessNum = AllNums - ErrorNum;
File.Delete(FilePath); //先删除,再保存。
//将写入结果导出为Excel
GetExcelByDataTable(mydt, FilePath);
// 流程直接返回读取信息
if (IsFlow == "Y")
{ // 流程直接返回读取信息
return EssResult;
}
try
{
DataTable ErrorTable = mydt;// GetNewDataTable(mydt, "Process = '' ", "");
//DataRow[] foundRow;
//foundRow = ErrorTable.Select("Comments != ''");
//if (foundRow != null && foundRow.Count() > 0)
//{
// foreach (DataRow row in foundRow)
// {
// ErrorTable.Rows.Remove(row);
// }
//}
//ErrorTable.AcceptChanges();//对DataTable(全部)操作完之后,一定要执行这一步,否则结果不保存
//if (ErrorTable.Rows.Count > 0)
//result = GHR.Common.DBCommon.ToJson(ErrorTable);
}
catch (Exception ex)
{
result = "[{\"readerror\":\"" + ex.Message + "\"}]";
}
return result;
}
/// <summary>
/// 根据Excel和Sheet返回DataTable
/// </summary>
/// <param name="filePath">Excel文件地址</param>
/// <param name="sheetIndex">Sheet索引</param>
/// <returns>DataTable</returns>
public static DataTable GetDataTable(string filePath, int sheetIndex, Dictionary<string, object> NameContrast)
{
return GetDataSet(filePath, sheetIndex, NameContrast).Tables[0];
}
/// <summary>
/// 根据Excel返回DataSet
/// </summary>
/// <param name="filePath">Excel文件地址</param>
/// <param name="sheetIndex">Sheet索引,可选,默认返回所有Sheet</param>
/// <returns>DataSet</returns>
public static DataSet GetDataSet(string filePath, int? sheetIndex, Dictionary<string, object> NameContrast)
{
DataSet ds = new DataSet();
IWorkbook fileWorkbook;
string FileExt = Path.GetExtension(filePath);
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (FileExt == ".xls")
{
try
{
//fileWorkbook = new HSSFWorkbook(fs);
fileWorkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
}
catch (Exception ex)
{
throw ex;
}
}
else if (FileExt == ".xlsx")
{
try
{
fileWorkbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
}
catch (Exception ex)
{
throw ex;
}
}
else fileWorkbook = null;
}
for (int i = 0; i < fileWorkbook.NumberOfSheets; i++)
{
if (sheetIndex != null && sheetIndex != i)
continue;
DataTable dt = new DataTable();
ISheet sheet = fileWorkbook.GetSheetAt(i);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int j = 0; j < header.LastCellNum; j++)
{
object obj = new object();
if (FileExt == ".xls")
{
obj = GetValueTypeForXLS(header.GetCell(j) as HSSFCell);
}
else if (FileExt == ".xlsx")
{
obj = GetValueTypeForXLS(header.GetCell(j) as XSSFCell);
}
else { obj = null; }
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + j.ToString()));
}
else
{
dt.Columns.Add(new DataColumn(obj.ToString()));
//try
//{
// dt.Columns.Add(new DataColumn(NameContrast[obj.ToString()].ToString()));
//}
//catch (Exception)
//{
// dt.Columns.Add(new DataColumn(obj.ToString()));
//}
}
columns.Add(j);
}
//数据
IEnumerator rows = sheet.GetEnumerator();
int n = sheet.FirstRowNum + 1;
while (rows.MoveNext())
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int K in columns)
{
try
{
dr[K] = GetValueTypeForXLS(sheet.GetRow(n).GetCell(K) as HSSFCell);
if (FileExt == ".xls")
{
dr[K] = GetValueTypeForXLS(sheet.GetRow(n).GetCell(K) as HSSFCell);
}
else if (FileExt == ".xlsx")
{
dr[K] = GetValueTypeForXLS(sheet.GetRow(n).GetCell(K) as XSSFCell);
}
else dr[K] = null;
if (dr[K] != null && dr[K].ToString() != string.Empty)
{
hasValue = true;
}
}
catch
{
hasValue = false;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
n++;
}
ds.Tables.Add(dt);
}
return ds;
}
/// <summary>
/// 根据DataTable导出Excel
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="file">保存地址</param>
public static bool GetExcelByDataTable(DataTable dt, string file)
{
DataSet ds = new DataSet();
DataTable NewDT = dt.Copy();
ds.Tables.Add(NewDT);
return GetExcelByDataSet(ds, file);
}
/// <summary>
/// 根据DataSet导出Excel
/// </summary>
/// <param name="ds">DataSet</param>
/// <param name="file">保存地址</param>
public static bool GetExcelByDataSet(DataSet ds, string file)
{
try
{
IWorkbook fileWorkbook;
if (Path.GetExtension(file) == ".xls")
{
fileWorkbook = new HSSFWorkbook();
}
else
{
fileWorkbook = new XSSFWorkbook();
}
int index = 0;
foreach (DataTable dt in ds.Tables)
{
index++;
ISheet sheet = fileWorkbook.CreateSheet("Sheet" + index);
//表头
IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
// 隐藏首行
if (IsHideTopRow)
row.HeightInPoints = 1;
//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}
//转为字节数组
MemoryStream stream = new MemoryStream();
fileWorkbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 获取新增表的字段设定(导入需要)
/// </summary>
/// <param name="menuName"></param>
/// <returns></returns>
public static async Task<DataSet> GetTableColumn(ISqlSugarClient Db, int langId, int userId, string menuName, string jsonParam)
{
string SQL = String.Format(@"exec [PT_GHR30_GetExcelEditColumn] '{1}',0,{2},{3}, '{0}','Import'", menuName, jsonParam, langId, userId);
// 第一张表 表头设定
// 第二张表 写入默认值
DataSet ds = await Db.Ado.GetDataSetAllAsync("SqlGhr30" + "Demo", SQL);
return ds;
}
/// <summary>
/// 根据单元格将内容返回为对应类型的数据
/// </summary>
/// <param name="cell">单元格</param>
/// <returns>数据</returns>
private static object GetValueTypeForXLS(HSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
{
if (DateUtil.IsCellDateFormatted(cell))
return cell.DateCellValue.Value.ToString("yyyy-MM-dd HH:mm");
else
return cell.NumericCellValue;
}
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
/// <summary>
/// 根据单元格将内容返回为对应类型的数据
/// </summary>
/// <param name="cell">单元格</param>
/// <returns>数据</returns>
private static object GetValueTypeForXLS(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
{
if (DateUtil.IsCellDateFormatted(cell))
return cell.DateCellValue.Value.ToString("yyyy-MM-dd HH:mm");
else
return cell.NumericCellValue;
}
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#region 其他
public class Other
{
/// <summary>
/// 数字转ADC字母
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Num2ABCletter([Range(1, 300)] int value)
{
List<string> Level = new List<string>
{
"A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T",
"U","V","W","X","Y","Z",
};
value = value - 1;
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
int remainder = value % 26;//余数
int front = (value - remainder) / 26;//
if (front == 0)
{
return Level[remainder];
}
else if (front < 26)
{
return Level[front - 1] + Level[remainder];
}
else
{
return Num2ABCletter(front) + Level[remainder];
}
}
/// <summary>
/// SqlBulkCopy 批量更新数据
/// </summary>
/// <param name="dataTable">数据集</param>
/// <param name="crateTemplateSql">临时表创建字段</param>
/// <param name="updateSql">更新语句</param>
public static void BulkUpdateData(string con, DataTable dataTable, string crateTemplateSql, string updateSql)
{
// ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
//using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings[con].ConnectionString))
//{
// using (var command = new SqlCommand("", conn))
// {
// try
// {
// conn.Open();
// //数据库并创建一个临时表来保存数据表的数据
// Random ran = new Random();
// int n = ran.Next(100, 1000);
// command.CommandText = String.Format(" CREATE TABLE #CTemplateTable" + n.ToString() + " ({0})", crateTemplateSql);
// command.ExecuteNonQuery();
// //使用SqlBulkCopy 加载数据到临时表中
// using (var bulkCopy = new SqlBulkCopy(conn))
// {
// foreach (DataColumn dcPrepped in dataTable.Columns)
// {
// bulkCopy.ColumnMappings.Add(dcPrepped.ColumnName, dcPrepped.ColumnName);
// }
// bulkCopy.BulkCopyTimeout = 660;
// bulkCopy.DestinationTableName = "#CTemplateTable" + n.ToString();
// bulkCopy.WriteToServer(dataTable);
// bulkCopy.Close();
// }
// updateSql = updateSql.Replace("#CTemplateTable", "#CTemplateTable" + n.ToString());
// // 执行Command命令 使用临时表的数据去更新目标表中的数据 然后删除临时表
// command.CommandTimeout = 300;
// command.CommandText = updateSql;
// command.ExecuteNonQuery();
// }
// finally
// {
// conn.Close();
// }
// }
//}
}
}
#endregion
}