From dd8c87263b9cb45e8eee5a2f8539ae8280b211ca Mon Sep 17 00:00:00 2001 From: chenxiangxue <910695411@qq.com> Date: Thu, 13 Jun 2024 14:01:02 +0800 Subject: [PATCH] 1 --- .../Competition.Common.csproj | 23 + .../Competition.Common/GridPager.cs | 26 + .../Competition.Common/Util/DESEncrypt.cs | 116 +++++ .../Util/EncryptionAndDecryption.cs | 133 +++++ .../Competition.Common/Util/RSAHelper.cs | 85 ++++ .../Competition.Common/Util/Tool.cs | 453 ++++++++++++++++++ 6 files changed, 836 insertions(+) create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/Competition.Common.csproj create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/GridPager.cs create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/Util/DESEncrypt.cs create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/Util/EncryptionAndDecryption.cs create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/Util/RSAHelper.cs create mode 100644 CompetitionAPI/CompetitionAPI/Competition.Common/Util/Tool.cs diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/Competition.Common.csproj b/CompetitionAPI/CompetitionAPI/Competition.Common/Competition.Common.csproj new file mode 100644 index 0000000..4fb166c --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/Competition.Common.csproj @@ -0,0 +1,23 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + ..\packages\zKeyAccess.dll + + + + diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/GridPager.cs b/CompetitionAPI/CompetitionAPI/Competition.Common/GridPager.cs new file mode 100644 index 0000000..b46aa6b --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/GridPager.cs @@ -0,0 +1,26 @@ +namespace Competition.Common +{ + public class GridPager + { + public int rows { get; set; }//每页行数 + public int page { get; set; }//当前页是第几页 + public string order { get; set; }//排序方式 + public string sort { get; set; }//排序列 + public int totalRows { get; set; }//总行数 + public int totalPages //总页数 + { + get + { + return (int)Math.Ceiling((float)totalRows / (float)rows); + } + } + public string filterRules { get; set; } + } + + + public class GridRows + { + public List rows { get; set; } + public int total { get; set; } + } +} \ No newline at end of file diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/Util/DESEncrypt.cs b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/DESEncrypt.cs new file mode 100644 index 0000000..06f5122 --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/DESEncrypt.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace Competition.Common.Util +{ + /// + /// DES加密/解密类。 + /// + public class DESEncrypt + { + public DESEncrypt() + { + } + + #region ========加密======== + + /// + /// 加密 + /// + /// + /// + public static string Encrypt(string Text) + { + return Encrypt(Text, "litianping"); + } + /// + /// 加密数据 + /// + /// + /// + /// + public static string Encrypt(string Text, string sKey) + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + byte[] inputByteArray; + inputByteArray = Encoding.Default.GetBytes(Text); + des.Key = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + StringBuilder ret = new StringBuilder(); + foreach (byte b in ms.ToArray()) + { + ret.AppendFormat("{0:X2}", b); + } + return ret.ToString(); + } + + #endregion + + #region ========解密======== + + + /// + /// 解密 + /// + /// + /// + public static string Decrypt(string Text) + { + return Decrypt(Text, "weqwq"); + } + /// + /// 解密数据 + /// + /// + /// + /// + public static string Decrypt(string Text, string sKey) + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + int len; + len = Text.Length / 2; + byte[] inputByteArray = new byte[len]; + int x, i; + for (x = 0; x < len; x++) + { + i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); + inputByteArray[x] = (byte)i; + } + des.Key = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + return Encoding.Default.GetString(ms.ToArray()); + } + + /// + /// 32位MD5加密 + /// + /// + /// + public static string Md5Hash(string input) + { + MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); + byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + return sBuilder.ToString().ToUpper(); + } + #endregion + + + } +} diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/Util/EncryptionAndDecryption.cs b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/EncryptionAndDecryption.cs new file mode 100644 index 0000000..1102147 --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/EncryptionAndDecryption.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace Competition.Common.Util +{ + public class EncryptionAndDecryption + { + #region ========加密======== + + /// + /// md5密码加密 + /// + /// + /// + public static string GetMD5(string passWord) + { + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] bt = Encoding.Default.GetBytes(passWord);//将待加密字符转为 字节型数组 + byte[] resualt = md5.ComputeHash(bt);//将字节数组转为加密的字节数组 + string pwds = BitConverter.ToString(resualt).Replace("-", ""); + passWord = pwds; + return passWord; + } + + /// + /// 加密 + /// + /// + /// + public static string Encrypt(string Text) + { + return Encrypt(Text, string.Format("NJ-{0}-ZGD", DateTime.Now.ToString("yyyy-MM-dd-HH"))); + } + + /// + /// 加密 + /// + /// + /// + public static string EncryptByLgzn(string Text) + { + return Encrypt(Text, "LGZN"); + } + + /// + /// 解密 + /// + /// + /// + public static string DecryptByLgzn(string Text) + { + return Decrypt(Text, "LGZN"); + } + /// + /// 加密数据 + /// + /// 明文 + /// 密钥 + /// + public static string Encrypt(string Text, string sKey) + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + byte[] inputByteArray; + inputByteArray = Encoding.Default.GetBytes(Text); + des.Key = ASCIIEncoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + StringBuilder ret = new StringBuilder(); + foreach (byte b in ms.ToArray()) + { + ret.AppendFormat("{0:X2}", b); + } + return ret.ToString(); + } + + #endregion + + #region ========解密======== + + + /// + /// 解密 + /// + /// + /// + public static string Decrypt(string Text) + { + return Decrypt(Text, string.Format("NJ-{0}-ZGD", DateTime.Now.ToString("yyyy-MM-dd-HH"))); + } + /// + /// 解密数据 + /// + /// 密文 + /// 密钥 + /// + public static string Decrypt(string Text, string sKey) + { + try + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + int len; + len = Text.Length / 2; + byte[] inputByteArray = new byte[len]; + int x, i; + for (x = 0; x < len; x++) + { + i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); + inputByteArray[x] = (byte)i; + } + des.Key = ASCIIEncoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + return Encoding.Default.GetString(ms.ToArray()); + } + catch + { + return null; + } + } + + #endregion + } +} diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/Util/RSAHelper.cs b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/RSAHelper.cs new file mode 100644 index 0000000..cf5a750 --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/RSAHelper.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Org.BouncyCastle.Asn1.Pkcs; +using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Pkcs; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.X509; + +namespace Competition.Common.Util +{ + public static class RSAHelper + { + private static string privateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDZMSy18BMV0Nae1slMI96v0U53BNF7nxWPL1Pbfz+5RBjKhMcKV9AIIqfKzh6UcITQPQHsP+TaEr1T7G7WFa/W/iUf6f63l241Uarexrn6k6ryPXO15zdb7CVwWCmVgmrvxcFgZgNvJ+Ga7kp4N4iayJxzCerda+KB9lg9tO8a/ZiypcOlOn7+zSFCyth4BOvYy6GIGFAbKctS8oIRxa938Y0HIzEl0nCXST4hlb4OIIOY1f1DCPbccXtT46buMRkL4uL+PYwcDkLh4S1XOBULhVkRNU4hwu/9QO5+cCWd5MkrYTGj7hgUSD1LWyGmpTP2yFIGXwkX0MzZrcoqbFzjAgMBAAECggEBAMA1+7qb11gUNQvnS8hdakMwuf8svXNpC3xnRxBW4f9Em6gGr9ugcRPyD4q0tW1q0q8zfpMkzJSNxw4RjNlb4f0jd5lxzSGPG1KGjvCO8KIosz2kUtXl5SEtsMhmzY5qF9dQrN1yCpIBunAReMhBZVyOM56/ZSJFyvR3HgqmKIE50YsrV6/kteLfZCa1uYmNbSEtNcMLrXlhvHbjWf8hd9W2MjxO9ZIbStPNEXGnA1hGJBCiUQjBYP+/rJudLUe8hsF4hJ8+flO1ZSyNxmrNBEfzzV7X9oEM+e5otF07pzd8snoZZe8x0CLBlqmfTivd7I3cMCQI/ocDIF0Mt2Bqy4ECgYEA9VyPXs8T4yJrai5Ui4NXbxBBP8r19KScxhNe9scZTRR4o/ABrQwX+yRdfSz72KTisRRqzfz2T+Zbwpj/U/kyfaGgqeF60JdwxHLjvnR+F+R+2zY9MIVR/oyVD8nM42BYUpnStUjd3EbOq/NuP88/cJdJpFdhGyVARc/+dH7pOkECgYEA4pvxHpESbxsnjtMy/g+hAaR/87w39fvKmVye05NT+YTGWiG5LVY3dJea4/w0SNLK6QCkFLXzCoh+jKbhXyPBhXlHIqRzim41DIwQeYZi7wu9Cx0s/yfEaxWsF3WcrPnagmTskTaKLbPFDCduJu9ywXi65Zjz7xqasyY2HVtz5iMCgYEAq9+OvscoEy+FNvgFWUVD9hTY4Cr4Z8r31viyyQNnAcuZRp1VTzbthYtPwePE91lpQsoelvTgRdAD7yjlkpk5eS/DL703Hu82myYvyrYnreztv/kam+aILVuk/05JK+3NcO833q2QXEFtfJ4lWKWAtwoDGA/tgepyP3UXtdtA3QECgYBKOwL1HFiJhL+kjZJ6nuwC+bvgP5ulPGHVcv2kGPK9Hb1L8RgTvdZUnwTiAc+uuz40rT0Se7etj6DEujXBUJkn+95NfslKY2eFQKx04oyt+Y5ngZsnygMRgPvqg2BbWU02wZCs0Mzaw7Sckp4GqxFQRxgR9dSSUoiyfqXjX/3LOQKBgQDAe63xXpMcFMp6xhvklOi8qNOfqGJttD4XhqJAQiUL7fblKAINxScrGSQQR+QKDTExiUkWhVYicpMq0CajwOPwXTC0xNBC9k5YP+yo+k+e+uRiUDjZGJekEzyJnXKJCCT2U23s172ltqsobsSfjXLVwHm2cg1gMwedo3455S8QtA=="; + + // 解密数据 + public static string DecryptData(string content) + { + var private_key = ToXmlPrivateKey(privateKey); + var data = Convert.FromBase64String(content); + string encryptedContent = string.Empty; + using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) + { + rsa.FromXmlString(private_key); + byte[] encryptedData = rsa.Decrypt(data, false); + encryptedContent = Encoding.UTF8.GetString(encryptedData); + } + return encryptedContent; + } + + /// + /// base64 private key string -> xml private key + /// + /// + /// + public static string ToXmlPrivateKey(string privateKey) + { + RsaPrivateCrtKeyParameters privateKeyParams = + PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)) as RsaPrivateCrtKeyParameters; + using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) + { + RSAParameters rsaParams = new RSAParameters() + { + Modulus = privateKeyParams.Modulus.ToByteArrayUnsigned(), + Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(), + D = privateKeyParams.Exponent.ToByteArrayUnsigned(), + DP = privateKeyParams.DP.ToByteArrayUnsigned(), + DQ = privateKeyParams.DQ.ToByteArrayUnsigned(), + P = privateKeyParams.P.ToByteArrayUnsigned(), + Q = privateKeyParams.Q.ToByteArrayUnsigned(), + InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned() + }; + rsa.ImportParameters(rsaParams); + return rsa.ToXmlString(true); + } + } + + /// + /// base64 public key string -> xml public key + /// + /// + /// + public static string ToXmlPublicKey(string pubilcKey) + { + RsaKeyParameters p = + PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters; + using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) + { + RSAParameters rsaParams = new RSAParameters + { + Modulus = p.Modulus.ToByteArrayUnsigned(), + Exponent = p.Exponent.ToByteArrayUnsigned() + }; + rsa.ImportParameters(rsaParams); + return rsa.ToXmlString(false); + } + } + } +} diff --git a/CompetitionAPI/CompetitionAPI/Competition.Common/Util/Tool.cs b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/Tool.cs new file mode 100644 index 0000000..5643959 --- /dev/null +++ b/CompetitionAPI/CompetitionAPI/Competition.Common/Util/Tool.cs @@ -0,0 +1,453 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Emit; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using SkiaSharp; +using Microsoft.VisualBasic; +using Org.BouncyCastle.Utilities.Collections; +using System.Data; +using NPOI.SS.UserModel; +using NPOI.XSSF.UserModel; +using NPOI.HSSF.UserModel; + +namespace Competition.Common.Util +{ + /// + /// 接口状态码 + /// + public enum APICode + { + /// + /// 成功 + /// + Success, + /// + /// 失败 + /// + Fail + } + + /// + /// 工具类 + /// + public class Tool + { + private static string appkey = "bridge-fenglin0903"; + private static int vs = 0; + + /// + /// 获取当前时间戳13位 + /// + /// + public static long GetTimestamp() + { + TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间 + return (long)ts.TotalMilliseconds; //精确到毫秒 + //return (long)ts.TotalSeconds;//获取10位 + } + + /// + /// 获取带状态码的JSON字符串 + /// + /// + /// + /// + public static object GetJsonWithCode(APICode code, object dataObj) + { + return new { code = (int)code, state = code.ToString(), data = dataObj }; + } + + /// + /// 将c# DateTime时间格式转换为Unix时间戳格式 + /// + /// 时间 + /// long + public static long DateTimeToTimestamp(System.DateTime time) + { + System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); + long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 + return t; + } + + /// + /// 时间戳转换为DATETIME格式 + /// + /// 时间戳字符串 + /// + public static DateTime GetDateTime(string timeStamp) + { + DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + string ts = timeStamp + "0000000"; + if (timeStamp.Length == 13) + { + ts = timeStamp + "0000"; + } + long lTime = long.Parse(ts); + TimeSpan toNow = new TimeSpan(lTime); + return dtStart.Add(toNow); + } + + /// + /// md5密码加密 + /// + /// 待加密字符串 + /// + public static string GetMD5(string passWord) + { + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] bt = Encoding.Default.GetBytes(passWord);//将待加密字符转为 字节型数组 + byte[] resualt = md5.ComputeHash(bt);//将字节数组转为加密的字节数组 + string pwds = BitConverter.ToString(resualt).Replace("-", ""); + passWord = pwds; + return passWord; + } + + /// + /// 图片转成base64 + /// + /// + /// + public static string img_to_base64(string Imagefilename) + { + try + { + using (MemoryStream memoryStream = new MemoryStream()) + { + Bitmap file = new Bitmap(Imagefilename); + file.Save(memoryStream, file.RawFormat); + file.Dispose(); + byte[] imageBytes = memoryStream.ToArray(); + return Convert.ToBase64String(imageBytes); + } + } + catch (Exception) + { + return ""; + } + } + + /// + /// 生成图片 + /// + /// 名称 + /// 起点 + /// 终点 + /// 型号长度 + /// 生成图片后的路径 + /// wwwroot文件 + public static bool GeneratePictures(string name, string start, string end, string model_length, string path, string root_path) + { + try + { + // 加载底图 + using (var inputStream = System.IO.File.OpenRead(root_path + "/Img/BaseMap.jpg")) + using (var original = SKBitmap.Decode(inputStream)) + { + // 创建一个新的位图对象,用于绘制 + using (var bitmap = new SKBitmap(original.Width, original.Height)) + { + // 将底图绘制到新的位图对象上 + using (var canvas = new SKCanvas(bitmap)) + { + canvas.DrawBitmap(original, 0, 0); + } + + // 在新的位图对象上绘制文本 + using (var canvas = new SKCanvas(bitmap)) + { + using (var paint = new SKPaint()) + { + //paint.Color = SKColors.Black; + //paint.TextSize = 30; + + //// 在底图上绘制文本 + //canvas.DrawText(name, 100, 100, paint); + //canvas.DrawText(start, 100, 150, paint); + //canvas.DrawText(end, 100, 200, paint); + // 获取当前操作系统的平台 + PlatformID platform = Environment.OSVersion.Platform; + SKTypeface typeface = SKTypeface.FromFile(""); + // 判断操作系统平台 + if (platform == PlatformID.Win32NT || platform == PlatformID.Win32S || platform == PlatformID.Win32Windows || platform == PlatformID.WinCE) + { + //Console.WriteLine("Windows 操作系统"); + // 加载自定义中文字体 + typeface = SKTypeface.FromFile("C:\\Windows\\Fonts\\msyh.ttc"); + } + else + { + typeface = SKTypeface.FromFile("/usr/share/fonts/msyh.ttc"); + } + // + paint.Typeface = typeface; + + paint.Color = SKColors.Black; + paint.TextSize = 50; + + // 在底图上绘制中文文本 + canvas.DrawText(name, 240, 195, paint); + canvas.DrawText(start, 240, 270, paint); + canvas.DrawText(end, 240, 345, paint); + canvas.DrawText(model_length, 360, 420, paint); + canvas.DrawText("配电工程处", 360, 495, paint); + canvas.DrawText("2019年8月16日", 240, 570, paint); + } + } + + // 将位图保存为图片文件 + using (var image = SKImage.FromBitmap(bitmap)) + using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) + using (var outputStream = System.IO.File.OpenWrite(root_path + path)) + { + data.SaveTo(outputStream); + } + } + } + return true; + } + catch (Exception ex) + { + return false; + } + } + + public static bool CopyAndRenameImage(string sourcePath, string destinationPath) + { + try + { + // 使用File.Copy方法复制图片 + File.Copy(sourcePath, destinationPath, true); // 第三个参数为true表示如果目标文件存在则覆盖 + return true; + } + catch (Exception ex) + { + } + return false; + } + + public static DataTable ExcelToDataTable(Stream fs, string suffix, string sheetName, int startRow, bool isFirstRowColumn, bool cshz) + { + DataTable dataTable = null; + DataColumn column = null; + DataRow dataRow = null; + IWorkbook workbook = null; + ISheet sheet = null; + IRow row = null; + ICell cell = null; + int cellCount = 0; + // int startRow = 0; + try + { + // 2007版本 + if (suffix == ".xlsx") + workbook = new XSSFWorkbook(fs); + // 2003版本 + else if (suffix == ".xls") + workbook = new HSSFWorkbook(fs); + + if (workbook != null) + { + if (sheetName != null) + { + sheet = workbook.GetSheet(sheetName); + if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet + { + if (cshz) + { + return null; + } + sheet = workbook.GetSheetAt(0); + } + } + else + { + sheet = workbook.GetSheetAt(0); + } + dataTable = new DataTable(); + if (sheet != null) + { + int rowCount = sheet.LastRowNum;//总行数 + if (rowCount > 0) + { + IRow firstRow = sheet.GetRow(startRow);//第一行 + int rowindex = 0; //搜索空行,并跳过 + while (firstRow == null && rowindex < rowCount) + { + rowindex++; + firstRow = sheet.GetRow(rowindex); + } //如果全为空行则返回null值 + if (rowindex == rowCount) return null; + + cellCount = firstRow.LastCellNum;//列数 + startRow = firstRow.RowNum; + // 构建datatable的列 + if (isFirstRowColumn) + { + //如果第一行是列名,则从第二行开始读取 + for (int i = firstRow.FirstCellNum; i < cellCount; ++i) + { + cell = firstRow.GetCell(i); + if (cell != null) + { + if (cell.ToString() != null) + { + column = new DataColumn(cell.ToString()); + dataTable.Columns.Add(column); + } + } + } + startRow++; + } + else + { + for (int i = firstRow.FirstCellNum; i < cellCount; ++i) + { + column = new DataColumn("column" + (i + 1)); + dataTable.Columns.Add(column); + } + } + + // 填充行 + for (int i = startRow; i <= rowCount; ++i) + { + row = sheet.GetRow(i); + if (row == null) continue; + cellCount = row.LastCellNum; //全文行之间的列数不一样的话,继续添加列 + if (cellCount > dataTable.Columns.Count) + { + for (int c = dataTable.Columns.Count; c < cellCount; c++) + { + column = new DataColumn("column" + (c + 1)); + dataTable.Columns.Add(column); + } + } + dataRow = dataTable.NewRow(); + for (int j = row.FirstCellNum; j < cellCount; ++j) + { + cell = row.GetCell(j); + if (cell == null) + { + dataRow[j] = ""; + } + else + { + // CellType(Unknown = -1, Numeric = 0, String = 1, Formula = 2, Blank = 3, Boolean = 4, Error = 5,) + switch (cell.CellType) + { + case CellType.Blank: + dataRow[j] = ""; + break; + case CellType.Numeric: + short format = cell.CellStyle.DataFormat; + // 对时间格式(2015.12.5、2015 / 12 / 5、2015 - 12 - 5等)的处理 + if (format == 14 || format == 31 || format == 57 || format == 58) + dataRow[j] = cell.DateCellValue; + else + dataRow[j] = cell.NumericCellValue; + break; + case CellType.String: + dataRow[j] = cell.StringCellValue; + break; + } + } + } + dataTable.Rows.Add(dataRow); + } + } + } + } + return dataTable; + } + catch (Exception ex) + { + if (fs != null) + { + fs.Close(); + } + return null; + } + } + + + public static string GetNumber() + { + var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + var NewId = ""; + NewId = string.Format("{0}{1}{2}", array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First()); + return NewId; + } + + public static string GetLongId() + { + return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0)); + } + + /// + /// 角色 + /// + public static Dictionary DicRole = new Dictionary() + { + {"0","超级管理员"} , {"1","管理员"} , {"2","学员"} + }; + + /// + /// 新ID + /// + /// + /// + public static string GetNewId(string flag) + { + string NewId = string.Format("{0}{1}", flag.ToUpper(), GetNewId()); + return NewId; + } + private static object lockObject = new object(); + + public static string GetNewId(bool sync = true) + { + var d = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0)); + var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + var NewId = ""; + if (!sync) + { + NewId = string.Format("{0}{1}{2}{3}{4}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), d.Next(0, 1000).ToString().PadLeft(3, '0'), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First()); + return NewId; + } + lock (lockObject) + { + System.Threading.Thread.Sleep(1); + NewId = string.Format("{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")); + return NewId; + } + } + + /// + /// 判断是否能使用 + /// + /// + public static bool CheckClose() + { + try + { + vs = zKeyAccess.KeyUtil.GetAccess(appkey); + if (vs <= 0) + { + return true; + } + else + { + return false; + } + } + catch (Exception ex) + { + return true; + } + } + } +}