using System.Data; using System.Globalization; using System.Text.RegularExpressions; namespace YLErp.Commons { /// /// 用于读取解析DataRow数据 /// public class DataRowReader { DataRow _row; readonly Dictionary _colMap; public DataRowReader(DataTable table, int headRowIndex = -1) { var colCount = table.Columns.Count; _colMap = new Dictionary(colCount, StringComparer.OrdinalIgnoreCase); for (var index = 0; index < colCount; index++) { if (headRowIndex >= 0) { var row = table.Rows[headRowIndex]; var col = row[index]?.ToString()?.Trim(); if (string.IsNullOrEmpty(col)) continue; _colMap[col.Replace("%", "")] = index; } else { var columns = table.Columns; var colName = columns[index].ColumnName; colName = colName.Replace("%", "").Trim(); _colMap[colName] = index; } } } /// /// 设置datarow /// public void SetDataRow(DataRow row) { _row = row; } public string GetString(string fieldName, bool required) { var str = _colMap.TryGetValue(fieldName, out var colIndex) ? _row[colIndex]?.ToString()?.Trim() : null; if (required && string.IsNullOrEmpty(str)) { throw new ServiceException($"{fieldName} 必须填写"); } return str; } public double? GetDouble(string fieldName, bool required) { var str = GetString(fieldName, required); if (!required && string.IsNullOrEmpty(str)) { return null; } return double.TryParse(str, out var num) ? num : throw new ServiceException($"{fieldName} 填写错误"); } public int? GetInt(string fieldName, bool required) { var str = GetString(fieldName, required); if (!required && string.IsNullOrEmpty(str)) { return null; } return int.TryParse(str, out var num) ? num : throw new ServiceException($"{fieldName} 填写错误"); } /// /// 获取百分比格式的数值 /// public double? GetPercent(string fieldName, bool required) { var str = GetString(fieldName, required); if (!required && string.IsNullOrEmpty(str)) { return null; } var isPercent = str.EndsWith("%"); if (isPercent) { str = str.TrimEnd('%'); } return double.TryParse(str, out var num) ? (isPercent ? num / 100 : num) : throw new ServiceException($"{fieldName} 填写错误"); } /// /// 获取百分比格式的数值 /// public decimal? GetDecimalPercent(string fieldName, bool required) { var str = GetString(fieldName, required); if (!required && string.IsNullOrEmpty(str)) { return null; } var isPercent = str.EndsWith("%"); if (isPercent) { str = str.TrimEnd('%'); } return decimal.TryParse(str, out var num) ? (isPercent ? num / 100 : num) : throw new ServiceException($"{fieldName} 填写错误"); } /// /// 获取日期(不包括时间) /// public DateTime? GetDate(string fieldName, bool required) { var str = GetString(fieldName, required); if (!required && string.IsNullOrEmpty(str)) { return null; } if (str.Length == 8 && Regex.IsMatch(str, @"^\d+$")) { return DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt2) ? dt2 : throw new ServiceException($"{fieldName} 填写错误"); } return DateTime.TryParse(str, out var dt) ? dt.Date : throw new ServiceException($"{fieldName} 填写错误"); } } }