#region 前端选中导入把文件存在服务器上
var
formData =
new
FormData();
formData.append(
"file"
, $(
"#upload"
)[0].files[0]);
$.ajax({
url:
"https://mxgcrm-api.lvshou.com/Upload/UploadFiles"
,
type:
'POST'
,
data: formData,
// 告诉jQuery不要去处理发送的数据
processData:
false
,
// 告诉jQuery不要去设置Content-Type请求头
contentType:
false
,
beforeSend:
function
() {
console.log(
"正在进行,请稍候"
);
},
success:
function
(responseStr) {
console.log(responseStr);
},
error:
function
(responseStr) {
console.log(
"error"
);
}
});
//后端上传文件方法
public MyJsonResult UploadFiles()
{
MyJsonResult jsonResult = new MyJsonResult();
object Data = new { };
try
{
HttpFileCollectionBase filelist = Request.Files;
string resourceDirectoryName = System.Configuration.ConfigurationManager.AppSettings["uploadUrl"];
string path = Server.MapPath(resourceDirectoryName);
if (filelist != null && filelist.Count > 0)
{
for (int i = 0; i < filelist.Count; i++)
{
HttpPostedFileBase file = filelist[i];
string fileName = file.FileName;
string ext = Path.GetExtension(fileName);
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ext;
fileName = Path.Combine(path, newFileName);
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists) { di.Create(); }
file.SaveAs(fileName);
Data = new { code = ReturnCode.访问成功, msg = ReturnCode.访问成功.ToString(), data = new { fileName = newFileName } };
}
}
else
{
Data = new { code = ReturnCode.尚未选择文件, msg = ReturnCode.尚未选择文件.ToString(), data = new { fileName = "" } };
}
}
catch (Exception ex)
{
Data = new { code = ReturnCode.服务器发生错误, msg = ReturnCode.服务器发生错误.ToString(), data = new { } };
}
jsonResult.Data = Data;
return jsonResult;
}
#endregion
#region 导入方法
/// <summary>
/// 导入初级资源(18/07/23 新版本)
/// </summary>
/// <param name="Params"></param>
/// <returns></returns>
public object ImportResources(string Params)
{
try
{
Hashtable jd = JsonConvert.DeserializeObject<Hashtable>(Params);
string FileName = Convert.ToString(jd["fileName"]);
string fileExt = Path.GetExtension(FileName).ToLower();
if (fileExt == ".xls" || fileExt == ".xlsx")
{
string resourceDirectoryName = ConfigurationManager.AppSettings["uploadUrl"];
string fileName = HttpContext.Current.Server.MapPath(resourceDirectoryName + FileName);
DataTable dt = ExcelToTable(fileName);//调用导入datatable方法
List<Msg> listMsg = new List<Msg>();
// int rowCount = 0;
foreach (DataRow item in dt.Rows)
{
cinfo = new CustomerResourcesInfo();
Msg msg = new Msg();
if (item["客户名称"] != null && item["客户名称"].ToString() != "")
{
cinfo.CustomerName = item["客户名称"].ToString().Trim();
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "客户姓名不能为空";
}
if (item["客户来源"] != null && item["客户来源"].ToString() != "")
{
List<V_Category_TypeInfo> listcate = new BaseBLL<V_Category_TypeInfo>().GetList("CategoryID,CategoryName", "IsDelete=0 and KeyName='CustomerSource'", "", null);
foreach (var item1 in listcate)
{
if (item1.CategoryName == item["客户来源"].ToString().Trim())
{
cinfo.CustomerSource = item1.CategoryID;
}
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "客户来源不能为空";
}
if (item["渠道"] != null && item["渠道"].ToString() != "")
{
if (cinfo.CustomerSource != null)
{
List<V_Category_TypeInfo> listcate = new BaseBLL<V_Category_TypeInfo>().GetList("CategoryID,CategoryName", "IsDelete=0 and ParentID=@ParentID", "", new List<DBParameter>() { new DBParameter("@ParentID", cinfo.CustomerSource) });
foreach (var item1 in listcate)
{
if (item1.CategoryName == item["渠道"].ToString().Trim())
{
cinfo.Channeling = item1.CategoryID;
}
}
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "渠道不能为空";
}
if (item["关键词"] != null && item["关键词"].ToString() != "")
{
cinfo.KeyWord = item["关键词"].ToString().Trim();
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "关键词不能为空";
}
if (item["搜索引擎"] != null && item["搜索引擎"].ToString() != "")
{
List<V_Category_TypeInfo> listcate = new BaseBLL<V_Category_TypeInfo>().GetList("CategoryID,CategoryName", "IsDelete=0 and KeyName='SearchEngines'", "", null);
foreach (var item1 in listcate)
{
if (item1.CategoryName == item["搜索引擎"].ToString().Trim())
{
cinfo.SearchEngine = item1.CategoryID;
}
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "搜索引擎不能为空";
}
if (item["日期"] != null && item["日期"].ToString() != "")
{
cinfo.CreateDate = Convert.ToDateTime(item["日期"]);
}
if (item["跟进状态"] != null && item["跟进状态"].ToString() != "")
{
List<V_Category_TypeInfo> listcate = new BaseBLL<V_Category_TypeInfo>().GetList("CategoryID,CategoryName", "IsDelete=0 and KeyName='FollowStatus'", "", null);
foreach (var item1 in listcate)
{
if (item1.CategoryName == item["跟进状态"].ToString().Trim())
{
cinfo.FollowStatus = item1.CategoryID;
}
}
}
if (item["手机"] != null && item["手机"].ToString() != "")
{
cinfo.Tel = item["手机"].ToString().Trim();
}
if (item["客户类型"] != null && item["客户类型"].ToString() != "")
{
List<V_Category_TypeInfo> listcate = new BaseBLL<V_Category_TypeInfo>().GetList("CategoryID,CategoryName", "IsDelete=0 and KeyName='CustomerType'", "", null);
foreach (var item1 in listcate)
{
if (item1.CategoryName == item["客户类型"].ToString().Trim())
{
cinfo.CustomerType = item1.CategoryID;
}
}
}
if (item["QQ或微信"] != null && item["QQ或微信"].ToString() != "")
{
cinfo.QQorWeixin = item["QQ或微信"].ToString().Trim();
}
if (item["网址"] != null && item["网址"].ToString() != "")
{
cinfo.URL = item["网址"].ToString().Trim();
}
if (item["备注"] != null && item["备注"].ToString() != "")
{
cinfo.Remark = item["备注"].ToString().Trim();
}
if (item["性别"] != null && item["性别"].ToString() != "")
{
cinfo.Sex = item["性别"].ToString().Trim();
}
if (item["设备"] != null && item["设备"].ToString() != "")
{
if (item["设备"].ToString().Trim() == "手机")
{
cinfo.Store = "1";
}
else if (item["设备"].ToString().Trim() == "电脑")
{
cinfo.Store = "2";
}
}
if (item["邮箱地址"] != null && item["邮箱地址"].ToString() != "")
{
cinfo.EmailAddress = item["邮箱地址"].ToString().Trim();
}
if (item["有无店铺"] != null && item["有无店铺"].ToString() != "")
{
if (item["有无店铺"].ToString().Trim() == "有")
{
cinfo.Store = "1";
}
else if (item["有无店铺"].ToString().Trim() == "无")
{
cinfo.Store = "2";
}
}
if (item["店铺名称"] != null && item["店铺名称"].ToString() != "")
{
cinfo.StoreName = item["店铺名称"].ToString().Trim();
}
if (item["邮编"] != null && item["邮编"].ToString() != "")
{
cinfo.PostCode = item["邮编"].ToString().Trim();
}
if (item["省份"] != null && item["省份"].ToString() != "")
{
RegionInfo rinfo = new Region().GetModel("", "District=@District and Level=1", "", new List<DBParameter>() { new DBParameter("@District", item["省份"].ToString().Trim()) });
if (rinfo != null && rinfo.District_id != null)
{
cinfo.Province = rinfo.District_id;
if (item["城市"] != null && item["城市"].ToString() != "")
{
RegionInfo rinfoCity = new Region().GetModel("", "District=@District and Level=2", "", new List<DBParameter>() { new DBParameter("@District", item["城市"].ToString().Trim()) });
if (rinfoCity != null && rinfoCity.District_id != null && !string.IsNullOrEmpty(cinfo.Province))
{
if (rinfoCity.Pid != null && rinfoCity.Pid == cinfo.Province)
{
cinfo.City = rinfoCity.District_id;
if (item["县/区"] != null && item["县/区"].ToString() != "")
{
RegionInfo rinfoCounty = new Region().GetModel("", "District=@District and Level=3", "", new List<DBParameter>() { new DBParameter("@District", item["县/区"].ToString().Trim()) });
if (rinfoCounty != null && rinfoCounty.District_id != null && !string.IsNullOrEmpty(cinfo.City))
{
if (rinfoCounty.Pid != null && rinfoCounty.Pid == cinfo.City)
{
cinfo.County = rinfoCounty.District_id;
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + item["省份"] + "不属于" + item["县/区"];
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "找不到" + item["县 / 区"].ToString();
}
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + item["城市"] + "不属于" + item["省份"];
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "找不到" + item["城市"].ToString();
}
}
}
else
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "找不到" + item["省份"].ToString();
}
}
if (string.IsNullOrEmpty(cinfo.Tel) && string.IsNullOrEmpty(cinfo.QQorWeixin))
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "手机号或微信号必须填一个";
}
cinfo.IsDelete = false;
cinfo.IsAllocation = false;
cinfo.IsPropagable = false;
cinfo.CreateBy = GetUserByToken().ID;
cinfo.LastEditBy = GetUserByToken().ID;
cinfo.LastEditDate = DateTime.Now;
cinfo.RealityFollowDate = DateTime.Now;
if (listc.Exists(x => !string.IsNullOrEmpty(x.Tel) && x.Tel == cinfo.Tel))
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "该手机号" + cinfo.Tel + "已存在";
}
if (!string.IsNullOrEmpty(cinfo.Tel))
{
if (cbll.Exists("Tel= ('" + cinfo.Tel + "')", null))
{
if (msg.msgInfo != null && msg.msgInfo != "")
{
msg.msgInfo = msg.msgInfo + ",";
}
msg.msgInfo = msg.msgInfo + "该手机号" + cinfo.Tel + "已存在";
}
}
if (msg.msgInfo == null || msg.msgInfo == "")
{
listc.Add(cinfo);
}
else
{
if (cinfo.Tel != null)
{
msg.msgTel = cinfo.Tel;
}
if (cinfo.CustomerName != null)
{
msg.msgCustomerName = cinfo.CustomerName;
}
listMsg.Add(msg);
}
}
cbll.Add(listc, "");
if (listMsg.Count > 0)
{
Data = ReturnFormat(ReturnCode.导入错误, "错误条数" + listMsg.Count + "条", listMsg);
}
else
{
Data = ReturnData(ReturnCode.访问成功, new { });
}
}
else
{
Data = ReturnData(ReturnCode.请选择excel文件, new { });
}
}
catch (Exception ex)
{
//2018、08、16 新增错误日志记录
AddOperationLog("CustomerResources", "001", "记录导入错误日志", ex.ToString(), OperationLogType.错误日志);
Data = ReturnData(ReturnCode.文件需要解密才能上传, new { });
}
return Data;
}
#endregion
#region Excel导入成Datable
/// Excel导入成Datable
/// </summary>
/// <param name="file">导入路径(包含文件名与扩展名)</param>
/// <returns></returns>
public DataTable ExcelToTable(string file)
{
DataTable dt = new DataTable();
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return null; }
ISheet sheet = workbook.GetSheetAt(0);
if (sheet.LastRowNum == sheet.FirstRowNum)
{
return dt;
}
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
//IRow header1 = sheet.GetRow(sheet.FirstRowNum + 1);
List<int> columns = new List<int>();
for (int i = 0; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
if (sheet.GetRow(i) == null)
{
}
else
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
if (sheet.GetRow(i).GetCell(j) == null)
{
dr[j] = "";
}
else if (sheet.GetRow(i).GetCell(j).CellType == CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(sheet.GetRow(i).GetCell(j)))
{
dr[j] = sheet.GetRow(i).GetCell(j).DateCellValue;
}
else if (sheet.GetRow(i).GetCell(j).CellType == CellType.Numeric)
{
dr[j] = sheet.GetRow(i).GetCell(j).NumericCellValue;
}
else
{
dr[j] = sheet.GetRow(i).GetCell(j).StringCellValue;
}
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
}
return dt;
}
#endregion
#region 获取单元格类型
/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private object GetValueType(ICell 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:
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;
}
}
#endregion