dlmh_system/VRS/Util/BasePage.cs

959 lines
35 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Telerik.Web.UI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using System.Threading;
using System.Configuration;
namespace VRS
{
/// <summary>
/// 接口状态码
/// </summary>
public enum APICode
{
/// <summary>
/// 成功
/// </summary>
Success,
/// <summary>
/// 失败
/// </summary>
Fail
}
public abstract class BasePage : System.Web.UI.Page
{
/// <summary>
/// md5密码加密
/// </summary>
/// <param name="passWord"></param>
/// <returns></returns>
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;
}
#region
/// <summary>
/// 根据属性名称获取值
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="strAttribute">属性名</param>
/// <returns>object</returns>
private static object GetValueByStrAttribute(object obj, string strAttribute)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null == propertyInfoName)
{
throw new Exception("属性名:" + strAttribute + " 不存在!");
}
return propertyInfoName.GetValue(obj, null);
}
#endregion
#region
/// <summary>
/// 根据属性名称设置值
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="strAttribute">属性名</param>
/// <param name="value">值</param>
public static void SetValueByStrAttribute(object obj, string strAttribute, object value)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null != propertyInfoName)
{
if (propertyInfoName.PropertyType == typeof(Nullable<Int32>) || propertyInfoName.PropertyType == typeof(Int32))
{
int int_value = 0;
if (int.TryParse(value.ToString(), out int_value))
{
propertyInfoName.SetValue(obj, int_value, null);
}
}
else if (propertyInfoName.PropertyType == typeof(Nullable<decimal>) || propertyInfoName.PropertyType == typeof(decimal))
{
decimal decimal_value = 0;
if (decimal.TryParse(value.ToString(), out decimal_value))
{
propertyInfoName.SetValue(obj, decimal_value, null);
}
propertyInfoName.SetValue(obj, decimal_value, null);
}
else
{
propertyInfoName.SetValue(obj, value, null);
}
}
}
#endregion
/// <summary>
/// 验证手机号码是否符合标准
/// </summary>
/// <param name="mobile"></param>
/// <returns></returns>
public static bool IsMobile(string mobile)
{
return System.Text.RegularExpressions.Regex.IsMatch(mobile, @"^(13|14|15|16|17|18|19)\d{9}$");
}
public static Dictionary<string, string> DicKsMode()
{
var DicSysType = ConfigurationManager.AppSettings["KsMode"];
var array1 = DicSysType.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dic = new Dictionary<string, string>();
for (var i = 0; i < array1.Length; i++)
{
var sub = array1[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var value = sub[0];
var text = sub[1];
dic.Add(value, text);
}
return dic;
}
protected void BindRole(RadDropDownList control, string defaultItem = null)
{
var dic = DicRole();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
foreach (var item in dic)
{
control.Items.Add(new DropDownListItem(item.Value, item.Key));
}
}
/// <summary>
/// 是否管理员
/// </summary>
/// <param name="user_role_key"></param>
/// <returns></returns>
public static bool isAdmin(string user_role_key)
{
var dic = DicRole();
if (dic.ContainsKey(user_role_key))
{
string role_name = dic[user_role_key];
if(role_name.Contains("管理员"))
{
return true;
}
}
return false;
}
private static Dictionary<string, string> _dicRole;
public static Dictionary<string, string> DicRole()
{
if (null == _dicRole)
{
var DicSysType = ConfigurationManager.AppSettings["RoleMode"];
var array1 = DicSysType.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dic = new Dictionary<string, string>();
for (var i = 0; i < array1.Length; i++)
{
var sub = array1[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var value = sub[0];
var text = sub[1];
dic.Add(value, text);
}
_dicRole = dic;
}
return _dicRole;
}
/// <summary>
/// 是否IP地址
/// </summary>
/// <param name="IP"></param>
/// <returns></returns>
public static bool IsIP(string IP)
{
return System.Text.RegularExpressions.Regex.IsMatch(IP, @"^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$");
}
public static int GetPosition()
{
return (int)long.Parse(DateTime.Now.ToString("yMdHms"));
}
/// <summary>
/// 新ID
/// </summary>
/// <param name="flag"></param>
/// <returns></returns>
public static string GetNewId(string flag)
{
string NewId = string.Format("{0}{1}", flag.ToUpper(), DateTime.Now.ToString("yMdHmsffff"));
return NewId;
}
public static string GetRandom()
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var value = array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First();
return value;
}
public static string GetRandomSeed()
{
Random r = new Random();
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
r = new Random(iSeed);
var rtn = r.Next(0, 10000).ToString().PadLeft(4, '0');
return rtn;
}
public static int GetRandomSeed(int min,int max)
{
Random r = new Random();
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
r = new Random(iSeed);
var rtn = r.Next(min, max + 1);
return rtn;
}
public static string GetNewId()
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var NewId = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.ToString("yyyyMMddHHmmssff"), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
/// <summary>
/// DateTime时间格式转换为10位不带毫秒的Unix时间戳
/// </summary>
/// <returns>Unix时间戳格式</returns>
public static long ConvertDateTimeInt(DateTime dt)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return (long)(dt - startTime).TotalSeconds;
}
private static Object Lockobj = new object();
/// <summary>
/// 获取房间号
/// </summary>
/// <returns></returns>
public static string GetId()
{
lock (Lockobj)
{
Thread.Sleep(1000);
var val = ConvertDateTimeInt(DateTime.Now);
return val.ToString();
}
}
public static int GetIntWidth(int count)
{
return Math.Abs(count).ToString().Length;
}
public static string GetNewId(int pos, int count)
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var width = GetIntWidth(count);
var position = pos.ToString().PadLeft(width, '0');
var NewId = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.ToString("yyyyMMddHHmmssff"), position, array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
/// <summary>
/// 获取基础设备状态
/// </summary>
/// <returns></returns>
public static Dictionary<int, string> GetBaseDeviceState()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["DeviceState"];
Dictionary<int, string> dic = new Dictionary<int, string>();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
var sub = item.Split(':');
var key = int.Parse(sub[0]);
var value = sub[1];
dic.Add(key, value);
}
}
return dic;
}
/*
/// <summary>
/// 绑定scene类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindSceneType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_scene bll = new DataService.BLL.mr_scene();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.scene_name, item.id));
});
}
*/
/*
/// <summary>
/// 绑定设备类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindEquipMentType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_device_type bll = new DataService.BLL.mr_device_type();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.device_type_name, item.id));
});
}
*/
/// <summary>
/// 绑定设备类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindBasePatrolType(RadDropDownList control, string defaultItem = null)
{
var majors = GetBasePatrolType();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
foreach (var item in majors)
{
control.Items.Add(new DropDownListItem(item.Value, item.Key.ToString()));
}
}
/*
/// <summary>
/// 绑定设备类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindScene(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_scene bll = new DataService.BLL.mr_scene();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.scene_name, item.id));
});
}
*/
/// <summary>
/// 绑定存在单位
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindExistsUnits( RadComboBox control, string defaultItem = null)
{
DataService.BLL.admin_user bll = new DataService.BLL.admin_user();
var majors = bll.GetUnitValues();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new RadComboBoxItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new RadComboBoxItem(item, item));
});
}
/// <summary>
/// 获取基础设备状态
/// </summary>
/// <returns></returns>
public static Dictionary<int, string> GetBasePatrolType()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["PatrolType"];
Dictionary<int, string> dic = new Dictionary<int, string>();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
var sub = item.Split(':');
var key = int.Parse(sub[0]);
var value = sub[1];
dic.Add(key, value);
}
}
return dic;
}
/// <summary>
/// 获取基础设备类型
/// </summary>
/// <returns></returns>
public static List<string> GetBaseDeviceType()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["DeviceType"];
List<string> list = new List<string>();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
list.AddRange(array);
}
return list;
}
/// <summary>
/// 绑定软件类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindSoft(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_soft bll = new DataService.BLL.admin_soft();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.soft_name, item.soft_id));
});
}
/// <summary>
/// 绑定专业
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindMajors(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_major bll = new DataService.BLL.admin_major();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.major_name, item.major_id));
});
}
/// <summary>
/// 绑定专业科目
/// </summary>
/// <param name="major_id">专业id</param>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindMajorSubject(string major_id, RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_subject bll = new DataService.BLL.admin_subject();
var majors = bll.GetModelList(" major_id='" + major_id + "'");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.subject_name, item.subject_id));
});
}
public void BindYears(RadDropDownList control, string defaultItem = null)
{
var dpYear = control;
var year = DateTime.Now.Year;
dpYear.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
for (int i = 0; i < 20; i++)
{
var currentYear = (year - i).ToString();
dpYear.Items.Add(new DropDownListItem(currentYear, currentYear));
}
}
/*
/// <summary>
/// 绑定专业
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindMajors(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.base_major bllMajor = new DataService.BLL.base_major();
var majors = bllMajor.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(major =>
{
control.Items.Add(new DropDownListItem(major.major, major.major));
});
if (majors.Count > 0)
{
control.SelectedIndex = 1;
}
}
*/
/// <summary>
/// 绑定设备类型
/// </summary>
/// <param name="parent_id">父类型id</param>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindDeviceType(string parent_id, RadDropDownList control, string defaultItem = null)
{
DataService.BLL.pro_type_manage bll = new DataService.BLL.pro_type_manage();
var majors = bll.GetModelList(string.Format(" parent_id = '{0}' ", parent_id));
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.type_name, item.type_name));
});
}
/*
/// <summary>
/// 绑定设备类型
/// </summary>
/// <param name="control"></param>
/// <param name="defaultItem"></param>
protected void BindProDeviceType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.pro_device_type bll = new DataService.BLL.pro_device_type();
var majors = bll.GetModelList("").OrderBy(s => s.type_name_zh).ToList();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.type_name_zh, item.id));
});
}
*/
/// <summary>
/// 根据名称获取类型
/// </summary>
/// <param name="typeName"></param>
protected DataService.Model.pro_type_manage GetTypeByName(string typeName)
{
DataService.BLL.pro_type_manage bllType = new DataService.BLL.pro_type_manage();
var models = bllType.GetModelList(string.Format(" type_name = '{0}' ", typeName));
if (models.Any())
return models.First();
else
{
var model = new DataService.Model.pro_type_manage { type_id = Guid.NewGuid().ToString(), type_name = typeName };
if (bllType.Add(model))
return model;
}
return null;
}
/// <summary>
/// 获取将对象转换为的JSON字符串
/// </summary>
/// <param name="dataObj"></param>
/// <returns></returns>
protected string GetJson(object dataObj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(dataObj);
}
/// <summary>
/// 获取带状态码的JSON字符串
/// </summary>
/// <param name="code"></param>
/// <param name="dataObj"></param>
/// <returns></returns>
protected string GetJsonWithCode(APICode code, object dataObj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { code = (int)code, state = code.ToString(), data = dataObj });
}
public static bool SaveFile(UploadedFile fileUpload, HttpContext httpContext, out string filePath)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//string fileName = Guid.NewGuid().ToString() + fileUpload.GetExtension();
string fileName = GetId()+ fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
public static bool SaveFileWithName(UploadedFile fileUpload, HttpContext httpContext,string Name, out string filePath)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
string fileName = Name + fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
public static bool SaveFile(UploadedFile fileUpload, HttpContext httpContext, out string filePath, out string originalName)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
originalName = fileUpload.FileName;
var index = originalName.LastIndexOf(".");
var prefix = originalName.Substring(0, index);
string fileName = prefix + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
/// <summary>
/// 页面初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void Page_Load(object sender, EventArgs e)
{
DataService.BLL.admin_user.load_login();
}
protected override void OnError(EventArgs e)
{
base.OnError(e);
var error = Server.GetLastError();
if (null != error)
{
write_log(error.ToString());
Response.Redirect("~/Util/Error.aspx?msg=" + error.Message);
}
}
/// <summary>
/// 根据Web.Config中SystemName系统名称判断菜单是否显示
/// </summary>
/// <param name="system_name"></param>
/// <returns></returns>
public static string menu_show_by_SystemName(string system_name)
{
var SystemName = System.Configuration.ConfigurationManager.AppSettings["SystemName"];
if (SystemName.ToUpper() == "ALL")
return "";
if (system_name == SystemName)
{
return "";
}
return "hidden";
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="msg"></param>
public static void write_log(string msg)
{
DateTime now = DateTime.Now;
HttpContext context = HttpContext.Current;
if (!Directory.Exists(context.Server.MapPath("/bin/logs/")))
{
Directory.CreateDirectory(context.Server.MapPath("/bin/logs/"));
}
StreamWriter sw = new StreamWriter(context.Server.MapPath("/bin/logs/" + now.ToString("yyyy-MM-dd") + ".txt"), true);
sw.Write("=============================================================\r\n" + now + "\r\n" + msg + "\r\n");
sw.Close();
}
public static void HttpGet(string url, Action<bool, string, string> callback, string Method = "GET")
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = Method;
req.ContentType = "application/json;charset=UTF-8";
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
callback(true, "", result);
}
catch (WebException ex)
{
//返回异常
var errorSr = new StreamReader(ex.Response.GetResponseStream());
string errMsg = errorSr.ReadToEnd();
Console.WriteLine(errMsg);
callback(false, errMsg, "");
}
}
public static DataTable ExcelToDataTable(string filePath, string sheetName, int startRow, bool isFirstRowColumn, bool cshz)
{
DataTable dataTable = null;
FileStream fs = 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
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
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;
}
}
}
}