///--------------------------------------------------------------------------
/// 文 件 名:PublicFuction.cs
/// 功能描述:公用方法类
/// CheckIPAddress:判断IP地址
/// IsMatchWith :判断格式(正则表达式)
/// ExportToExcel :导出Excel文件
///--------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using GeneralLib;
using System.Threading;
using System.Security.Principal;
namespace SunVoteARSPPT
{
class PublicFunction
{
///
/// 检查IP地址合法性
///
///
public static bool CheckIPAddress(string sIPAddress)
{
bool isOK = false;
string[] ary = sIPAddress.Split('.');
if (ary.Length == 4)
{
isOK = true;//成功
for (int i = 0; i < ary.Length; i++)
{
int num = -1;
if (int.TryParse(ary[i], out num))
{
if ((num < 0) || (num > 255))
{
isOK = false;
break;
}
}
else
{
isOK = false;
break;
}
}
}
return isOK;
}
///
/// 判断字符是否符合格式
///
///
///
///
public static bool IsMatchWith(String str, String pattern)
{
if (str == null)
{
return false;
}
return new Regex(pattern).IsMatch(str);
}
///
/// 导出Excel表格。杨斌 2019-05-29
///
public static void ExportToExcelEx(System.Windows.Forms.DataGridView grd, string titleName)
{
try
{
ExcelOper exl = new ExcelOper();
exl.NewExcel();
Microsoft.Office.Interop.Excel.Worksheet oSheet = exl.GetSheetByNum(1);
ExcelOper.SetSheetName(oSheet, titleName);
var ran = ExcelOper.GetRange(oSheet, 1, 1, grd.RowCount + 1, 1);
//ran.Columns.AutoFit();
ran.ColumnWidth = 20;
ran.Rows.WrapText = true;
ExcelOper.SetRangeColor(ran, grd.ColumnHeadersDefaultCellStyle.BackColor);
ran = ExcelOper.GetRange(oSheet, 1, 1, grd.RowCount + 1, 1);
ran.RowHeight = 30;
ran = ExcelOper.GetRange(oSheet, 1, 2, 1, grd.ColumnCount + 1);
ran.ColumnWidth = 5;
ran = ExcelOper.GetRange(oSheet, 1, 1, grd.RowCount + 1, grd.ColumnCount + 1);
ExcelOper.SetBorderLine(ran);
for (int col = 0; col < grd.Columns.Count; col++)
{
int r = 1;
int c = col + 2;
oSheet.Cells[r, c] = grd.Columns[col].HeaderText;
ran = ExcelOper.GetRange(oSheet, r, c, r, c);
//ran.ColumnWidth = grd.Columns[col].Width;
ExcelOper.SetRangeColor(ran, grd.ColumnHeadersDefaultCellStyle.BackColor);
}
for (int row = 0; row < grd.Rows.Count; row++)
{
int r = row + 2;
int c = 1;
oSheet.Cells[r, c] = grd.Rows[row].HeaderCell.Value;
ran = ExcelOper.GetRange(oSheet, r, c, r, c);
//ran.RowHeight = grd.Rows[row].Height;
ExcelOper.SetRangeColor(ran, grd.RowHeadersDefaultCellStyle.BackColor);
for (int col = 0; col < grd.Columns.Count; col++)
{
r = row + 2;
c = col + 2;
//oSheet.Cells[r, c] = "";
ran = ExcelOper.GetRange(oSheet, r, c, r, c);
ExcelOper.SetRangeColor(ran, grd.Rows[row].Cells[col].Style.BackColor);
}
}
exl.ShowExcel(true);
}
catch (Exception ex)
{
SystemLog.WriterLog(ex);
}
}
///
/// 导出Excel表格
///
/// 导出表格控件
/// 标题
/// true:导出成功,false:未导出
public static bool ExportToExcel(System.Windows.Forms.DataGridView grd, string titleName)
{
string fileName = "";
System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.InitialDirectory = "C:\\";
//saveFileDialog.Filter = "Execl files (*.xls)|*.xls|Excel files (*.xlsx)|*.xlsx";
saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx";//杨斌 2018-12-18。不兼容2003格式
//saveFileDialog.FilterIndex = (Convert.ToDouble(excelApplication.Version) >= 12) ? 2 : 1;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = saveFileDialog.FileName;
}
else
{
return false;
}
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelApplication.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet lastWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);
Microsoft.Office.Interop.Excel.Worksheet newSheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing);
// string excelVertion = (Convert.ToDouble(excelApplication.Version) > 12) ? "xlsx" : "xls";
newSheet.Name = titleName;
for (int col = 0; col < grd.Columns.Count; col++)
{
newSheet.Cells[1, col + 1] = grd.Columns[col].HeaderText;
}
for (int row = 0; row < grd.Rows.Count; row++)
{
for (int col = 0; col < grd.Columns.Count; col++)
{
newSheet.Cells[row + 2, col + 1] = (grd.Rows[row].Cells[col].Value != null ? grd.Rows[row].Cells[col].Value.ToString() : "");
}
}
try
{
workbook.Close(true, fileName, System.Reflection.Missing.Value);
}
catch (Exception e)
{
throw e;
}
excelApplication.Quit();
KillExcel();
return true;
}
///
/// 关闭EXCEL进程
///
private static void KillExcel()
{
Process[] excelProcesses = Process.GetProcessesByName("EXCEL");
DateTime startTime = new DateTime();
int processId = 0;
for (int i = 0; i < excelProcesses.Length; i++)
{
if (startTime < excelProcesses[i].StartTime)
{
startTime = excelProcesses[i].StartTime;
processId = i;
}
}
if (excelProcesses[processId].HasExited == false)
{
excelProcesses[processId].Kill();
}
}
///
/// 数字转换为字母
/// 创建 赵丽
///
///
public static string NumToABC(int iNum)
{
string option = "";
switch (iNum)
{
case 1:
option = "A";
break;
case 2:
option = "B";
break;
case 3:
option = "C";
break;
case 4:
option = "D";
break;
case 5:
option = "E";
break;
case 6:
option = "F";
break;
case 7:
option = "G";
break;
case 8:
option = "H";
break;
case 9:
option = "I";
break;
case 10:
option = "J";
break;
default:
break;
}
return option;
}
///
/// 判断两个数组是否完全相等
/// 创建 赵丽
///
///
///
///
public static bool AryIsEqual(string[] a, string[] b)
{
bool bResult = true;
if (a.Length != b.Length) { return false; }
for (int i = 0; i < a.Length; i++)
{
if (Array.IndexOf(b, a[i]) == -1)
{
bResult = false;
break;
}
}
for (int i = 0; i < b.Length; i++)
{
if (Array.IndexOf(a, b[i]) == -1)
{
bResult = false;
break;
}
}
return bResult;
}
///
/// 去掉末尾的指定字符串
///
///
///
///
public static string TrimEndStr(string sText, string sTrim)
{
string res = sText;
if (sText.Length > 0)
{
int len = sText.Length - sTrim.Length;
if ((len > 0) && (sText.Substring(len) == sTrim))
res = sText.Substring(0, len);
}
return res;
}
///
/// 数组排序
/// 修改:杨斌 2012-10-12 键盘数量=6000时,非常耗时。修改内部排序方式,不用冒泡。
///
///
///
public static string[] KeyIDSort()
{
string[] aryKeyIDStr = new string[GlobalInfo.hardwareManage.KeyStatus.Count];
int[] aryKeyID = new int[GlobalInfo.hardwareManage.KeyStatus.Count];
GlobalInfo.hardwareManage.KeyStatus.Keys.CopyTo(aryKeyIDStr, 0);
for (int i = 0; i < aryKeyID.Length; i++)
{
aryKeyID[i] = ConvertOper.Convert(aryKeyIDStr[i]).ToInt;
}
Array.Sort(aryKeyID);
for (int i = 0; i < aryKeyID.Length; i++)
{
aryKeyIDStr[i] = aryKeyID[i].ToString();
}
return aryKeyIDStr;
//string[] KeyIDList = new string[GlobalInfo.hardwareManage.KeyStatus.Count];
//for (int i = 0; i < KeyIDList.Length; i++) { KeyIDList[i] = "0"; }
//GlobalInfo.hardwareManage.KeyStatus.Keys.CopyTo(KeyIDList, 0);
////冒泡排序从小到大
//Array.Sort(KeyIDList);
//for (int i = 0; i < KeyIDList.Length; i++)
//{
// for (int j = i + 1; j < KeyIDList.Length; j++)
// {
// if (Convert.ToInt32(KeyIDList[i]) > Convert.ToInt32(KeyIDList[j]))
// {
// string iTemp = KeyIDList[i];
// KeyIDList[i] = KeyIDList[j];
// KeyIDList[j] = iTemp.ToString();
// }
// }
//}
//return KeyIDList;
}
public static char SplitItemScore = '|';//杨斌 2019-07-19
///
/// 从字符串获取选项分数字典,Key=选项编号,Item=分值
///
///
///
public static Dictionary GetItemScore(string optionScore)
{
Dictionary dicScore = new Dictionary();
try
{
string[] aryScore = optionScore.Split(SplitItemScore);
int num = 0;
for (int i = 0; i < aryScore.Length; i++)
{
string[] aryScoreItem = aryScore[i].Split('=');
double score = 0;
if (aryScoreItem.Length >= 2)
{
num = new ConvertOper(aryScoreItem[0]).ToInt;
score = new ConvertOper(aryScoreItem[1]).ToDouble;
if (!dicScore.ContainsKey(num))
dicScore.Add(num, score);
}
}
}
catch (Exception ex)
{
SystemLog.WriterLog(ex);
}
return dicScore;
}
///
/// 判断当前用户是否为管理员
/// 创建 赵丽 2012-04-12
///
///
public static bool IsAdministrator()
{
AppDomain myDomain = Thread.GetDomain();
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
return myPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
///
/// 转半角的函数
/// 创建标志 赵丽 2012-06-06
///
///
///
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
public static int ToInt(string strValue)
{
try
{
return Convert.ToInt32(strValue);
}
catch
{
return 0;
}
}
///
/// 获取字符串字节长度,即一个汉字长度为2倍
/// 创建:杨斌 2013-04-19
///
///
///
public static int StrLenByte(string str)
{
if (str != null)
return System.Text.Encoding.Default.GetByteCount(str);
else
return 0;
}
///
/// 判断路径格式是否正确有效
/// 杨斌 2014-12-05s
///
///
///
public static bool CheckPath(string path)
{
string pattern = @"^[a-zA-Z]:(((\\(?! )[^/:*?<>\""|\\]+)+\\?)|(\\)?)\s*$";
Regex regex = new Regex(pattern);
return regex.IsMatch(path);
}
}
}