您的位置:首页 > 其它

导入excel

2016-05-27 15:18 453 查看
.ascx文件

<div style="/*float: right; */width: 188px; margin-top: 3px; margin: 0 auto;">
<asp:Button runat="server" Text="导入"
CssClass="adminButtonBlue" ID="btnImportXLS" OnClick="btnImportXLS_Click" />
</div>

<div>
<span runat="server" id="spanMessageerr" style="color: Red;"></span> //提示信息
</div>


<ajaxToolkit:ConfirmButtonExtender ID="cbeImportXLS" runat="server" TargetControlID="btnImportXLS"

DisplayModalPopupID="mpeImportXLS" />

<ajaxToolkit:ModalPopupExtender runat="server" ID="mpeImportXLS" TargetControlID="btnImportXLS"

OkControlID="btnImportXLSOk" CancelControlID="btnImportXLSCancel" PopupControlID="pnlImportXLSPopupPanel"

BackgroundCssClass="modalBackground" />

<asp:Panel runat="server" ID="pnlImportXLSPopupPanel" Style="display: none; width: 250px;

border-width: 2px; border-color: Black; border-style: solid;

padding: 20px;">

<div style="text-align: center;">

<%=GetLocaleResourceString("Admin.Customers.ImportXLS.ExcelFile")%>

<asp:FileUpload runat="server" ID="fuXlsFile" />

<asp:Button ID="btnImportXLSOk" runat="server" Text="<% $NopResources:Admin.Common.OK %>"

CssClass="adminButton" CausesValidation="false" />

<asp:Button ID="btnImportXLSCancel" runat="server" Text="<% $NopResources:Admin.Common.Cancel

%>" CssClass="adminButton" CausesValidation="false" />

</div>

</asp:Panel>

.ascx.cs文件

//button按钮

protected void btnImportXLS_Click(object sender, EventArgs e)
{
if (fuXlsFile.PostedFile != null && !String.IsNullOrEmpty(fuXlsFile.FileName))
{
try
{
spanMessageok.InnerText = "";
byte[] fileBytes = fuXlsFile.FileBytes;
string extension = "xls";
if (fuXlsFile.FileName.EndsWith("xlsx"))
extension = "xlsx";

string fileName = string.Format("orders_{0}_{1}.{2}", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4), extension);
string filePath = string.Format("{0}files\\ExportImport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);

File.WriteAllBytes(filePath, fileBytes);
var result = this.ImportManager.ImportOrderFromXls(filePath);
if (result.Contains("ok"))
{
var topresult = result.Substring(0, 2);
var last = result.Substring(2);
if (topresult == "ok" && last == "")
{
manger.JscriptMsg(this.Parent.Parent.Page, "导入成功!", "#", "Success");
}
else if (topresult == "ok" && last != "")
{
if (last.Contains("/"))
{
var people = last.Substring(0, 1);
if (people == "/")
{
spanMessageerr.InnerText = "您当前要求导入的表格数据中未导入的数据序号为‘" + last.Substring(1) + "’请核对后再进行导入";
}
else
{
spanMessageerr.InnerText = "您当前要求导入的表格数据已在系统中存在,已存在的老数据序号:‘" + last.Substring(0, last.IndexOf("/")) + "’未导入的数据序号为‘" + last.Substring(last.IndexOf('/') + 1) + "’请核对后再进行导入";
}
}
else
{
spanMessageerr.InnerText = "您当前要求导入的表格数据已在系统中存在,已存在的老数据序号:‘" + last + "’请核对后再进行导入";
}
}
}
else if (result.Contains("/"))
{
var people = result.Substring(0, 1);
if (people == "/")
{
spanMessageerr.InnerText = "您当前要求导入的表格数据中未导入的数据序号为‘" + result.Substring(1) + "’请核对后再进行导入";
}
else
{
spanMessageerr.InnerText = "您当前要求导入的表格数据已在系统中存在,已存在的老数据序号:" + result.Substring(0, result.IndexOf("/")) + "’未导入的数据序号为‘" + result.Substring(result.IndexOf('/') + 1) + "’请核对后再进行导入";
}
}
else
{
spanMessageerr.InnerText = "您当前要求导入的表格数据已在系统中存在,已存在的老数据序号:'" + result + "’请核对后再进行导入";
}
}

catch (Exception ex)
{
ProcessException(ex);
}
}
}

.cs文件

/// <summary>
/// Import order list from XLS file
/// </summary>
/// <param name="filePath">Excel file path</param>
public string ImportOrderFromXls(string filePath)
{
string wrong = "";
string TiShi = "";
string NoPeople = "";
using (ExcelHelper excelHelper = new ExcelHelper(filePath))
{
excelHelper.Hdr = "YES";
excelHelper.Imex = "1";
#region 变量(为excel中数据列定义变量)
string num = ""; //序号
string addDate = "";
string outDate = "";
string CoName = "";
string CoWeChat = "";
string CoMobile = "";
string AgentName = "";
string AgentGrade = "";
string AgentWeChat = "";
string AgentMobile = "";
string ReceiverName = "";
string address = "";
string ReceiverPhone = "";
string orderType = "";
string productName = "";
string productCount = "";
string bags = "";
string handBag = "";
string bookCase = "";
string singlePage = "";
string outType = "";
string payType = "";
string emsName = "";
string emsNum = "";
#endregion
DataTable dt = excelHelper.ReadTable("orders");
var aaa = dt.Rows.Count;
foreach (DataRow dr in dt.Rows)
{
#region 获取excel中的数据

//也可以用 dr["列名"] 获取,但有时中文的不好识别,所以此处我用了列的位置,这样要导入的excel中的列不可调换位置

//因为excel的唯一标识只有这个序号,所以提示的时候提示哪个序号的数据存在问题
num = dr[0].ToString();
if (num == null || num == "")
{
break;
}

addDate = dr[1].ToString();

outDate = dr[2].ToString();

CoName = dr[3].ToString();

CoWeChat = dr[4].ToString();

CoMobile = dr[5].ToString();

AgentName = dr[6].ToString();

AgentGrade = dr[7].ToString();

AgentWeChat = dr[8].ToString();

AgentMobile = dr[9].ToString();

ReceiverName = dr[10].ToString();

ReceiverPhone = dr[11].ToString();

address = dr[12].ToString();

orderType = dr[13].ToString();

productName = dr[14].ToString();

productCount = dr[15].ToString();

bags = dr[16].ToString();

handBag = dr[17].ToString();

bookCase = dr[18].ToString();

singlePage = dr[19].ToString();

outType = dr[20].ToString();

payType = dr[21].ToString();

emsName = dr[22].ToString();

emsNum = dr[23].ToString();

//获取好值之后可以直接调用程序中的方法导入到相应的表中,此处我用了存储过程

Guid orderGuid = Guid.NewGuid();
Guid orderProductVariantGuid = Guid.NewGuid();
#endregion
#region 参数并调用存储过程(这样写的参数中文到sql中会自动前边加“N”)
ICommonService service = new CommonService();
try
{
using (SqlConnection connectionString = new SqlConnection(ZgNew.BusinessLogic.Configuration.NopConfig.ConnectionString))
{
connectionString.Open();
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@num",num),
new SqlParameter("@addDate",addDate),
new SqlParameter("@outDate",outDate),
new SqlParameter("@CoName ",CoName ),
new SqlParameter("@CoWeChat",CoWeChat),
new SqlParameter("@CoMobile",CoMobile),
new SqlParameter("@AgentName",AgentName),
new SqlParameter("@AgentGrade ",AgentGrade),
new SqlParameter("@AgentWeChat ",AgentWeChat),
new SqlParameter("@AgentMobile ",AgentMobile),
new SqlParameter("@ReceiverName ",ReceiverName),
new SqlParameter("@ReceiverPhone",ReceiverPhone),
new SqlParameter("@address",address),
new SqlParameter("@orderType",orderType),
new SqlParameter("@productName",productName),
new SqlParameter("@productCount",Convert.ToInt32(productCount)),
new SqlParameter("@bags",Convert.ToInt32(bags)),
new SqlParameter("@handBag",Convert.ToInt32(handBag)),
new SqlParameter("@bookCase",Convert.ToInt32(bookCase)),
new SqlParameter("@singlePage",Convert.ToInt32(singlePage)),
new SqlParameter("@outType",outType),
new SqlParameter("@payType",payType),
new SqlParameter("@emsName",emsName),
new SqlParameter("@emsNum",emsNum),
new SqlParameter("@orderGuid",orderGuid),
new SqlParameter("@applyGuid",NopContext.Current.User.CustomerGuid),
new SqlParameter("@applyName",NopContext.Current.User.Username),
new SqlParameter("@orderProductVariantGuid",orderProductVariantGuid),
new SqlParameter("@UserHostAddress", NopContext.Current.UserHostAddress),
new SqlParameter("@returnvalue",SqlDbType.NVarChar,500)

};
parms[29].Direction = ParameterDirection.Output;
service.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, "[dbo].[sp_inster_Orders]", parms);
#endregion

//判断返回值
if (parms[29].Value.ToString() == "err")
{
wrong += num + ",";
connectionString.Close();
}
else if (parms[29].Value.ToString() == "ok")
{
wrong = "ok";
}
else if (parms[29].Value.ToString() == "no")
{
NoPeople += num + ","; //为导入的数据序号
}
else if (parms[29].Value.ToString() == "old")
{
TiShi += num + ","; //老数据序号
}
}
;
}
catch (Exception ex)
{
wrong = "操作失败";
}
}
if (TiShi != "")
{
wrong = wrong + TiShi;
if (NoPeople != "")
{
wrong = wrong + "/" + NoPeople;
}
}
else if (NoPeople != "")
{
wrong = wrong + "/" + NoPeople;
}
}
return wrong;
}

sp_inster_Orders存储过程大概的内容

1、先要获取传过来的参数

2、判断条件,是否已存在,数据是否正确

3、已存在的返回‘old’,数据存在错误的返回‘no’,正确并导入的返回‘ok’

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: