导入EXCEL

用Aspose.Cells.dll 前提引用这个类库

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.Data.SqlClient;
using System.Data;
using Frensworkz.Crm40.Sohu.Web;
using System.Text.RegularExpressions;
using Aspose.Cells;
using System.Web.Services.Protocols;
using System.Xml;


namespace QotdApplyUpload
{
    public partial class QotdApplyUpload : System.Web.UI.Page
    {
        //private static SqlConnection CRMSQLConnStr = new SqlConnection("Data Source=10.1.34.107;Initial Catalog=GiftTest01_MSCRM;User Id=erp;Password=sa!@#$4321;");
        private List<string> CheckedData = new List<string>();
        private DataTable QotdApplysDataTable = new DataTable();
        private DataTable ApplyDepartmentDT = new DataTable();
        private DataTable ApplyUserDT = new DataTable();
        private static SqlConnection CRMSQLConnStr;
        private static CrmService QotdCrmService = new CrmService();
        private static string new_name = string.Empty;
        private static string orgname = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
         
            if (!Page.IsPostBack)
            {
                GetMSCRMDB();
                //new_name = "{36EEF889-C0F7-DF11-BAD7-005056A84A2D}";
                //orgname = "gifttest01";
                if (this.Request.QueryString["orgname"] != null && this.Request.QueryString["orgname"].Trim() != "" && this.Request.QueryString["orgname"].Trim().ToLower() != "null")
                {
                    orgname = this.Request.QueryString["orgname"].Trim();
                }
                if (this.Request.QueryString["id"] != null && this.Request.QueryString["id"].Trim() != "" && this.Request.QueryString["id"].Trim().ToLower() != "null")
                {
                    new_name = this.Request.QueryString["id"].Trim();
                }
                else
                {
                    this.lblMsg.Text = "必须通过在报价明细表单上的“导入报价明细”按钮进行明细的导入!";
                    this.fuImport.Enabled = false;
                    this.btnSubmit.Enabled = false;
                    return;
                }
                InitializeGiftCrmService(orgname);
            }

        }
        static void GetMSCRMDB()
        {

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("C:/SohuCRMConfig/SohuCRMConfig.xml");
            XmlNode ConfigNode = xmlDoc.SelectSingleNode("/SohuCRMConfigs/GiftConfigs");
            foreach (XmlNode item in ConfigNode.ChildNodes)
            {
                switch (item.Name)
                {
                    case "CRMSQLConnStr":
                        CRMSQLConnStr = new  SqlConnection( item.InnerText.Trim());
                        break;
                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            this.lblMsg.Text = "";
            if (!this.fuImport.HasFile)
            {
                this.lblMsg.Text = "请选择需要导入的报价明细!";
                return;
            }

            ImportObject importObj = UploadFile();
            if (importObj == null)
            {
                return;
            }
            string serverpath = Server.MapPath(@"\sohu\QotdApplyUpload\importfile\");
            //string serverpath = Server.MapPath(@"\importfile\");
            if (importObj.ImportMessageType == ImportObject.MessageType.Succeed)
            {
                try
                {
                    GetExcelDatas(serverpath + importObj.ImportFileName);
                    if (System.IO.File.Exists(serverpath + importObj.ImportFileName))
                    {
                        System.IO.File.Exists(serverpath + importObj.ImportFileName);
                    }
                    AnalyseGiftDatas();
                    AnalyseSupplierDatas();
                    Createnew_qotd();
                    this.lblMsg.Text = "报价单明细导入成功!<br>生成报价明细单:" + QotdApplysDataTable.Rows.Count.ToString() + "条数据。";
                    Response.Write("<script>window.returnValue = '报价明细导入成功'; </script> ");
                }
                catch (Exception ex)
                {

                    this.lblMsg.Text = ex.Message;
                    try
                    {
                        for (int i = 0; i < ApplyUserDT.Rows.Count; i++)
                        {
                            if (ApplyUserDT.Rows[i]["Director"] != null
                                && ApplyUserDT.Rows[i]["Director"].ToString() != "")
                            {
                                DeleteEntity("new_qotd", ApplyUserDT.Rows[i]["Director"].ToString());
                            }
                        }
                    }
                    catch (Exception DeleteError)
                    {
                        this.lblMsg.Text += "<br>" + DeleteError.Message;
                    }
                }
            }
            else
            {
                this.lblMsg.Text = importObj.ImportMessage;
            }

            if (System.IO.File.Exists(serverpath + importObj.ImportFileName))
            {
                System.IO.File.Delete(serverpath + importObj.ImportFileName);
            }
        }


        /// <summary> 初始化CRMWebService
        /// </summary>
        private static void InitializeGiftCrmService(string crmname)
        {
            QotdCrmService = new CrmService();
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = crmname;
            if (HttpContext.Current.Request.Url.IsDefaultPort == true) { QotdCrmService.Url = "http://" + System.Net.Dns.GetHostName() + "/mscrmservices/2007/crmservice.asmx"; }
            else { QotdCrmService.Url = "http://" + System.Net.Dns.GetHostName() + ":" + HttpContext.Current.Request.Url.Port + "/mscrmservices/2007/crmservice.asmx"; }

           // QotdCrmService.Url = "http://10.1.34.107/mscrmservices/2007/crmservice.asmx";
            QotdCrmService.CrmAuthenticationTokenValue = token;

            //QotdCrmService.Credentials = new System.Net.NetworkCredential("cssh", "sohu12345", "sohu-inc");
            QotdCrmService.Credentials = System.Net.CredentialCache.DefaultCredentials;


        }

        private ImportObject UploadFile()
        {
            ImportObject importObj = null;
            if (fuImport.HasFile)
            {
                importObj = new ImportObject(this.fuImport.PostedFile.FileName);
                string serverpath = Server.MapPath(@"\sohu\QotdApplyUpload\importfile\");
                //string serverpath = Server.MapPath(@"\importfile\");
                if (importObj.ImportFileType != "XLS" && importObj.ImportFileType != "XLSX" && importObj.ImportFileType != "ACCDB" && importObj.ImportFileType != "MDB")
                {
                    importObj.ImportMessageType = ImportObject.MessageType.Error;
                    importObj.ImportMessage = "对不起,系统不支持您所导入的文件格式!";
                }
                else if (this.fuImport.PostedFile.ContentLength > 20480000)
                {
                    importObj.ImportMessageType = ImportObject.MessageType.Error;
                    importObj.ImportMessage = "文件大小超过限制!";
                }
                else
                {
                    try
                    {
                        this.fuImport.PostedFile.SaveAs(serverpath + importObj.ImportFileName);
                        importObj.ImportMessageType = ImportObject.MessageType.Succeed;
                    }
                    catch (Exception ex)
                    {
                        importObj.ImportMessageType = ImportObject.MessageType.Error;
                        importObj.ImportMessage = ex.Message;
                    }
                }
            }
            return importObj;
        }

        private void GetExcelDatas(string fileName)
        {
            QotdApplysDataTable = new DataTable();
            Workbook workbook = new Workbook();
            workbook.Open(fileName);
            Worksheets wsts = workbook.Worksheets;
            if (wsts.Count > 0)
            {
                Worksheet wst = wsts[0];
                if (wst.Cells[2, 0].Value == null || wst.Cells[2, 0].Value.ToString().Trim() != "礼品")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第1列的列名“礼品”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 1].Value == null || wst.Cells[2, 1].Value.ToString().Trim() != "采购要求")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第2列的列名“采购要求”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 2].Value == null || wst.Cells[2, 2].Value.ToString().Trim() != "采购数量")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第3列的列名“采购数量”不匹配,请修改正确后再重新导入!");
                }
                //规格信息
                if (wst.Cells[2, 3].Value == null || wst.Cells[2, 3].Value.ToString().Trim() != "规格信息")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第4列的列名“规格信息”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 4].Value == null || wst.Cells[2, 4].Value.ToString().Trim() != "报价(单价)")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第5列的列名“报价(单价)”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 5].Value == null || wst.Cells[2, 5].Value.ToString().Trim() != "报价(总价)")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第6列的列名“报价(总价)”不匹配,请修改正确后再重新导入!");
                }
                //价格说明 
                if (wst.Cells[2, 6].Value == null || wst.Cells[2, 6].Value.ToString().Trim() != "价格说明")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第7列的列名“价格说明”不匹配,请修改正确后再重新导入!");
                }

                //确定打样天数 
                if (wst.Cells[2, 7].Value == null || wst.Cells[2, 7].Value.ToString().Trim() != "确定打样天数")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第8列的列名“确定打样天数”不匹配,请修改正确后再重新导入!");
                }


                //大活生产天数 
                if (wst.Cells[2, 8].Value == null || wst.Cells[2, 8].Value.ToString().Trim() != "大活生产天数")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第9列的列名“大活生产天数”不匹配,请修改正确后再重新导入!");
                }


                //价格有效日期
                if (wst.Cells[2, 9].Value == null || wst.Cells[2, 9].Value.ToString().Trim() != "价格有效日期")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第10列的列名“价格有效日期”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 10].Value == null || wst.Cells[2, 10].Value.ToString().Trim() != "最早供货日期")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第11列的列名“最早供货日期”不匹配,请修改正确后再重新导入!");
                }
                if (wst.Cells[2, 11].Value == null || wst.Cells[2, 11].Value.ToString().Trim() != "最迟供货日期")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第12列的列名“最迟供货日期”不匹配,请修改正确后再重新导入!");
                }
                //说明
                if (wst.Cells[2, 12].Value == null || wst.Cells[2, 12].Value.ToString().Trim() != "说明")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第13列的列名“说明”不匹配,请修改正确后再重新导入!");
                }

                if (wst.Cells[2, 13].Value == null || wst.Cells[2, 13].Value.ToString().Trim() != "供应商")
                {
                    throw new Exception("对不起,您导入的Excel数据格式模板不正确,与第14列的列名“供应商”不匹配,请修改正确后再重新导入!");
                }

                QotdApplysDataTable.Columns.Add("ImportIndex", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_gift_qotd_r", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_claim", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_num", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_spec", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_unitquote", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_totalquote", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_pricedetail", Type.GetType("System.String"));

                QotdApplysDataTable.Columns.Add("new_qotd_sampleday", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_proday", Type.GetType("System.String"));

                QotdApplysDataTable.Columns.Add("new_qotd_validdate", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_earlydate", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_latedate", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_detail", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_suppliername", Type.GetType("System.String"));
                QotdApplysDataTable.Columns.Add("new_qotd_supplierid", Type.GetType("System.Guid"));
                QotdApplysDataTable.Columns.Add("GiftGuid", Type.GetType("System.Guid"));
                //2010-11-12

                for (int rowIndex = 3; rowIndex < wst.Cells.MaxRow + 1; rowIndex++)
                {
                    DataRow QotdApplysDataRow = QotdApplysDataTable.NewRow();
                    QotdApplysDataRow[0] = rowIndex;
                    for (int columnIndex = 0; columnIndex < 14; columnIndex++)
                    {
                        if (columnIndex == 0 || columnIndex == 1 || columnIndex == 2 || columnIndex == 4 || columnIndex == 5 || columnIndex == 6 || columnIndex == 7 || columnIndex == 8 || columnIndex == 9 || columnIndex == 13)
                        {
                            if (wst.Cells[rowIndex, columnIndex].Value == null || wst.Cells[rowIndex, columnIndex].Value.ToString() == "")
                            {
                                throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列数据不能为空,请补充完整后再重新导入!");
                            }
                            else
                            {
                                //判断“采购数量”列的值是否为正整数?
                                if (columnIndex == 2 && !Regex.IsMatch(wst.Cells[rowIndex, columnIndex].Value.ToString(), @"^[0-9]*[1-9][0-9]*$"))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“数量”不能为非正整数(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");
                                }
                                // 判断单价是不是大于0  4
                                if (columnIndex == 4 && !IsNumber(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“报价(单价)”必须是大于0的自然数(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");
                                
                                }
                                //判断单价是不是大于0  5
                                if (columnIndex == 5 && !IsNumber(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“报价(总价)”必须是大于0的自然数(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");
                                
                                }
                                //天数7  2,147,483,647
                                if (columnIndex == 7 && !IsNumber2(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“确定打样天数”必须是大于0,小于 2,147,483,647 的整数(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");

                                }
                                //天数7  2,147,483,647
                                if ( columnIndex == 8 && !IsNumber2(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“大活生产天数”必须是大于0,小于 2,147,483,647 的整数(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");

                                }
                                //日期 9 10 11
                                if (columnIndex == 9 && !IsDate(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“价格有效日期“时间格式不对(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");

                                } 
                             
                                QotdApplysDataRow[columnIndex + 1] = wst.Cells[rowIndex, columnIndex].Value.ToString().Trim();
                                


                                
                            }
                        }
                        else
                        {
                            if (wst.Cells[rowIndex, columnIndex].Value == null || wst.Cells[rowIndex, columnIndex].Value.ToString() == "")
                            {
                                QotdApplysDataRow[columnIndex + 1] = null;
                            }
                            else
                            {
                                if (columnIndex == 10 && !IsDate(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“最早供货日期”时间格式不对(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");

                                } if (columnIndex == 11 && !IsDate(wst.Cells[rowIndex, columnIndex].Value.ToString()))
                                {
                                    throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + " 行第 " + (columnIndex + 1) + " 列“最迟供货日期”时间格式不对(" + wst.Cells[rowIndex, columnIndex].Value.ToString() + "),请修改正确后再重新导入!");

                                }
                                QotdApplysDataRow[columnIndex + 1] = wst.Cells[rowIndex, columnIndex].Value.ToString().Trim();
                            }
                        }
                    }
                    try
                    {
                        QotdApplysDataTable.Rows.Add(QotdApplysDataRow);
                    }
                    catch (Exception)
                    {
                        throw new Exception("对不起,您导入的Excel数据中第 " + (rowIndex + 1) + "行数据有问题,请修改正确后再重新导入!");
                        
                    }
                   
                }
            }
        }

        private void AnalyseSupplierDatas()
        {
            CheckedData.Clear();
            string Sqlstr = string.Empty;
            string Supplier = string.Empty;
            DataTable RetrievedDT = new DataTable();
            for (int i = 0; i < QotdApplysDataTable.Rows.Count; i++)
            {
                Sqlstr = string.Empty;
                Supplier = QotdApplysDataTable.Rows[i]["new_qotd_suppliername"].ToString();
                RetrievedDT = new DataTable();
                if (!CheckedData.Contains(Supplier))
                {
                    CheckedData.Add(Supplier);
                    Sqlstr = @"select ext.New_name as suppname,ext.New_supplierId suppid from New_supplierBase bas inner join 
                                New_supplierExtensionBase  ext on bas.New_supplierId= ext.New_supplierId
                                WHERE  bas.statecode = 0 and bas.DeletionStateCode = 0
                                AND new_name = '" + Supplier + "' ";
                    SQLExecuteQuery(Sqlstr, CRMSQLConnStr, RetrievedDT);
                    if (RetrievedDT.Rows.Count == 0)
                    {
                        throw new Exception("对不起,您导入的Excel数据中第 " + (i + 1) + " 行中未找到已经启用的供应商:" + Supplier + ",请核实修改正确后再重新导入!");
                    }
                    else if (RetrievedDT.Rows.Count > 1)
                    {
                        throw new Exception("对不起,您导入的Excel数据中第 " + (i + 1) + " 行中在系统中找到已经启用的相同名称的供应商:" + Supplier + ",请核实修改正确后再重新导入!");
                    }
                    else
                    {
                        QotdApplysDataTable.Rows[i]["new_qotd_supplierid"] = RetrievedDT.Rows[0]["suppid"];
                    }
                }
                else
                {
                    DataRow[] GiftGuidDR = QotdApplysDataTable.Select("new_qotd_supplierid IS NOT NULL AND new_qotd_suppliername = '" + Supplier + "'");
                    QotdApplysDataTable.Rows[i]["new_qotd_supplierid"] = GiftGuidDR[0]["new_qotd_supplierid"];

                }
            }
        }

        private void AnalyseGiftDatas()
        {
            CheckedData.Clear();
            string Sqlstr = string.Empty;
            string Gift = string.Empty;
            DataTable RetrievedDT = new DataTable();
            for (int i = 0; i < QotdApplysDataTable.Rows.Count; i++)
            {
                Sqlstr = string.Empty;
                Gift = QotdApplysDataTable.Rows[i]["new_gift_qotd_r"].ToString();
                RetrievedDT = new DataTable();
                if (!CheckedData.Contains(Gift))
                {
                    CheckedData.Add(Gift);
                    Sqlstr = @"SELECT new_giftBase.new_giftid,new_name,new_gift_unitprice,ISNULL(new_gift_class,1) AS new_gift_class
                                FROM new_giftBase
                                INNER JOIN new_giftExtensionBase ON new_giftBase.new_giftid = new_giftExtensionBase.new_giftid
                                WHERE new_giftBase.DeletionStateCode = 0
                                AND new_giftBase.StateCode = 0
                                AND new_name = '" + Gift + "' ";
                    SQLExecuteQuery(Sqlstr, CRMSQLConnStr, RetrievedDT);
                    if (RetrievedDT.Rows.Count == 0)
                    {
                        throw new Exception("对不起,您导入的Excel数据中第 " + (i + 1) + " 行中未找到已经启用的礼品:" + Gift + ",请核实修改正确后再重新导入!");
                    }
                    else if (RetrievedDT.Rows.Count > 1)
                    {
                        throw new Exception("对不起,您导入的Excel数据中第 " + (i + 1) + " 行中在系统中找到已经启用的相同名称的礼品:" + Gift + ",请核实修改正确后再重新导入!");
                    }
                    else
                    {
                        QotdApplysDataTable.Rows[i]["GiftGuid"] = RetrievedDT.Rows[0]["new_giftid"];
                    }
                }
                else
                {
                    //DataRow[] GiftGuidDR = QotdApplysDataTable.Select("GiftGuid IS NOT NULL AND new_gift_qotd_r = '" + Gift + "'");
                    //QotdApplysDataTable.Rows[i]["GiftGuid"] = GiftGuidDR[0]["GiftGuid"];
                    throw new Exception("对不起,您导入的Excel数据中第 " + (i + 1) + " 行,礼品:" + Gift + "已经存在相同记录!");

                }
            }
        }

        private static void SQLExecuteQuery(string CommandText, SqlConnection Connection, DataTable DT)
        {
            try
            {
                Connection.Open();
                SqlCommand SqlCmd = new SqlCommand(CommandText, Connection);
                SqlCmd.CommandTimeout = 0;
                SqlDataAdapter SqlDap = new SqlDataAdapter(SqlCmd);
                SqlDap.Fill(DT);
                SqlCmd.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("执行数据库操作失败: " + ex.Message + CommandText);
            }
            finally
            {
                Connection.Close();
            }
        }

        private void DeleteEntity(string entityName, string entityGuid)
        {
            try
            {
                TargetDeleteDynamic target = new TargetDeleteDynamic();
                target.EntityName = entityName;
                target.EntityId = new Guid(entityGuid);

                DeleteRequest delete = new DeleteRequest();
                delete.Target = target;

                DeleteResponse deleted = (DeleteResponse)QotdCrmService.Execute(delete);
            }
            catch (SoapException ex)
            {
                throw new Exception("删除单据失败: " + entityName + "、" + entityGuid + "," + ex.Detail.InnerText);
            }
        }

        /// <summary> 创建报价明细
        /// </summary>
        private void Createnew_qotd()
        {

            ApplyUserDT = new DataTable();
            ApplyUserDT.Columns.Add("Gifts", Type.GetType("System.Guid"));               //Gifts 礼品
            ApplyUserDT.Columns.Add("PurchasingRequirements", Type.GetType("System.String"));  //PurchasingRequirements  采购要求
            ApplyUserDT.Columns.Add("PurchasingNumber", Type.GetType("System.Int32"));  //PurchasingNumber 采购数量
            ApplyUserDT.Columns.Add("Spec", Type.GetType("System.String"));  //Spec 规格信息
            ApplyUserDT.Columns.Add("SinglePrice", Type.GetType("System.Decimal"));                 //SinglePrice 报价(单价)
            ApplyUserDT.Columns.Add("TotalPrice", Type.GetType("System.Decimal"));                  //TotalPrice 报价(总价)
            ApplyUserDT.Columns.Add("Pricedetail", Type.GetType("System.String"));                  //Pricedetail 价格说明

            ApplyUserDT.Columns.Add("Sampleday", Type.GetType("System.String"));                  //Pricedetail 价格说明
            ApplyUserDT.Columns.Add("Proday", Type.GetType("System.String"));                  //Pricedetail 价格说明

            ApplyUserDT.Columns.Add("Validdate", Type.GetType("System.String"));    //Validate 价格有效日期
            ApplyUserDT.Columns.Add("Earlydate", Type.GetType("System.String"));    //Earlydate 最早供货日期
            ApplyUserDT.Columns.Add("Latedate", Type.GetType("System.String"));     //Latedate 最晚供货日期
            ApplyUserDT.Columns.Add("Detail", Type.GetType("System.String"));                  //Detail 说明
            ApplyUserDT.Columns.Add("Remark", Type.GetType("System.String"));                  //Remark 备注
            ApplyUserDT.Columns.Add("Suppid", Type.GetType("System.Guid"));
            ApplyUserDT.Columns.Add("Director", Type.GetType("System.Guid"));
            //ApplyUserDT.Columns.Add("CreatedApplyDepartmentGuid", Type.GetType("System.Guid"));
            try
            {
                for (int i = 0; i < QotdApplysDataTable.Rows.Count; i++)
                {

                    DataRow ApplyUserDataRow = ApplyUserDT.NewRow();
                    ApplyUserDataRow["Gifts"] = QotdApplysDataTable.Rows[i]["GiftGuid"];
                    ApplyUserDataRow["PurchasingRequirements"] = QotdApplysDataTable.Rows[i]["new_qotd_claim"].ToString();
                    ApplyUserDataRow["PurchasingNumber"] = QotdApplysDataTable.Rows[i]["new_qotd_num"];
                    ApplyUserDataRow["Spec"] = QotdApplysDataTable.Rows[i]["new_qotd_spec"].ToString();
                    ApplyUserDataRow["SinglePrice"] = Decimal.Parse(QotdApplysDataTable.Rows[i]["new_qotd_unitquote"].ToString());
                    ApplyUserDataRow["TotalPrice"] = Decimal.Parse(QotdApplysDataTable.Rows[i]["new_qotd_totalquote"].ToString());
                    ApplyUserDataRow["Pricedetail"] = QotdApplysDataTable.Rows[i]["new_qotd_pricedetail"].ToString();

                    ApplyUserDataRow["Sampleday"] = QotdApplysDataTable.Rows[i]["new_qotd_sampleday"].ToString();
                    ApplyUserDataRow["Proday"] = QotdApplysDataTable.Rows[i]["new_qotd_proday"].ToString();


                    ApplyUserDataRow["Validdate"] = QotdApplysDataTable.Rows[i]["new_qotd_validdate"].ToString();
                    ApplyUserDataRow["Earlydate"] = QotdApplysDataTable.Rows[i]["new_qotd_earlydate"].ToString();
                    ApplyUserDataRow["Latedate"] = QotdApplysDataTable.Rows[i]["new_qotd_latedate"].ToString();
                    ApplyUserDataRow["Detail"] = QotdApplysDataTable.Rows[i]["new_qotd_detail"].ToString();
                    ApplyUserDataRow["Suppid"] = QotdApplysDataTable.Rows[i]["new_qotd_supplierid"].ToString();
                    ApplyUserDT.Rows.Add(ApplyUserDataRow);

                }
                for (int i = 0; i < ApplyUserDT.Rows.Count; i++)
                {
                    DynamicEntity CreateEntity = new DynamicEntity();
                    CreateEntity.Name = "new_qotd";

                    //礼品
                    LookupProperty new_gift_qotd_r = new LookupProperty();
                    new_gift_qotd_r.Name = "new_gift_qotd_r";
                    new_gift_qotd_r.Value = new Lookup();
                    new_gift_qotd_r.Value.Value = new Guid(ApplyUserDT.Rows[i]["Gifts"].ToString());
                    CreateEntity.Properties.Add(new_gift_qotd_r);

                    //供应商
                    LookupProperty new_supplier_qotd_r = new LookupProperty();
                    new_supplier_qotd_r.Name = "new_supplier_qotd_r";
                    new_supplier_qotd_r.Value = new Lookup();
                    new_supplier_qotd_r.Value.Value = new Guid(ApplyUserDT.Rows[i]["Suppid"].ToString());
                    CreateEntity.Properties.Add(new_supplier_qotd_r);


                    //报价单
                    LookupProperty new_qot_qotd_r = new LookupProperty();
                    new_qot_qotd_r.Name = "new_qot_qotd_r";
                    new_qot_qotd_r.Value = new Lookup();
                    new_qot_qotd_r.Value.Value = new Guid(new_name);
                    CreateEntity.Properties.Add(new_qot_qotd_r);

                    //采购要求
                    StringProperty new_qotd_claim = new StringProperty();
                    new_qotd_claim.Name = "new_qotd_claim";
                    new_qotd_claim.Value = ApplyUserDT.Rows[i]["PurchasingRequirements"].ToString();
                    CreateEntity.Properties.Add(new_qotd_claim);

                    //采购数量
                    CrmNumberProperty new_qotd_num = new CrmNumberProperty();
                    new_qotd_num.Name = "new_qotd_num";
                    new_qotd_num.Value = new CrmNumber();
                    new_qotd_num.Value.Value = Int32.Parse(ApplyUserDT.Rows[i]["PurchasingNumber"].ToString());
                    CreateEntity.Properties.Add(new_qotd_num);

                    //规格信息
                    if (string.IsNullOrEmpty(ApplyUserDT.Rows[i]["Spec"].ToString()) == false)
                    {
                        StringProperty new_qotd_spec = new StringProperty();
                        new_qotd_claim.Name = "new_qotd_spec";
                        new_qotd_claim.Value = ApplyUserDT.Rows[i]["Spec"].ToString();
                        CreateEntity.Properties.Add(new_qotd_claim);
                    }


                    //报价单价
                    CrmMoneyProperty new_qotd_unitquote = new CrmMoneyProperty();
                    new_qotd_unitquote.Name = "new_qotd_unitquote";
                    new_qotd_unitquote.Value = new CrmMoney();
                    new_qotd_unitquote.Value.Value = Decimal.Parse(ApplyUserDT.Rows[i]["SinglePrice"].ToString());
                    CreateEntity.Properties.Add(new_qotd_unitquote);

                    //报价总价
                    CrmMoneyProperty new_qotd_totalquote = new CrmMoneyProperty();
                    new_qotd_totalquote.Name = "new_qotd_totalquote";
                    new_qotd_totalquote.Value = new CrmMoney();
                    new_qotd_totalquote.Value.Value = Decimal.Parse(ApplyUserDT.Rows[i]["TotalPrice"].ToString());
                    CreateEntity.Properties.Add(new_qotd_totalquote);


                    //确定打样天数
                    CrmNumberProperty new_qotd_sampleday = new CrmNumberProperty();
                    new_qotd_sampleday.Name = "new_qotd_sampleday";
                    new_qotd_sampleday.Value = new CrmNumber();
                    new_qotd_sampleday.Value.Value = Int32.Parse(ApplyUserDT.Rows[i]["Sampleday"].ToString());
                    CreateEntity.Properties.Add(new_qotd_sampleday);


                    //大活生产天数
                    CrmNumberProperty new_qotd_proday = new CrmNumberProperty();
                    new_qotd_proday.Name = "new_qotd_proday";
                    new_qotd_proday.Value = new CrmNumber();
                    new_qotd_proday.Value.Value = Int32.Parse(ApplyUserDT.Rows[i]["Proday"].ToString());
                    CreateEntity.Properties.Add(new_qotd_proday);


                    //价格有效日期
                    CrmDateTimeProperty new_qotd_validdate = new CrmDateTimeProperty();
                    new_qotd_validdate.Name = "new_qotd_validdate";
                    new_qotd_validdate.Value = new CrmDateTime();
                    new_qotd_validdate.Value.Value = ApplyUserDT.Rows[i]["Validdate"].ToString();
                    CreateEntity.Properties.Add(new_qotd_validdate);

                    //报价说明
                    if (string.IsNullOrEmpty(ApplyUserDT.Rows[i]["Pricedetail"].ToString()) == false)
                    {
                        StringProperty new_qotd_pricedetail = new StringProperty();
                        new_qotd_pricedetail.Name = "new_qotd_pricedetail";
                        new_qotd_pricedetail.Value = ApplyUserDT.Rows[i]["Pricedetail"].ToString();
                        CreateEntity.Properties.Add(new_qotd_pricedetail);
                    }

                    //最早供货日期
                    if (string.IsNullOrEmpty(ApplyUserDT.Rows[i]["Earlydate"].ToString()) == false)
                    {
                        CrmDateTimeProperty new_qotd_earlydate = new CrmDateTimeProperty();
                        new_qotd_earlydate.Name = "new_qotd_earlydate";
                        new_qotd_earlydate.Value = new CrmDateTime();
                        new_qotd_earlydate.Value.Value = ApplyUserDT.Rows[i]["Earlydate"].ToString();
                        CreateEntity.Properties.Add(new_qotd_earlydate);
                    }

                    //最迟供货日期
                    if (string.IsNullOrEmpty(ApplyUserDT.Rows[i]["Latedate"].ToString()) == false)
                    {
                        CrmDateTimeProperty new_qotd_latedate = new CrmDateTimeProperty();
                        new_qotd_latedate.Name = "new_qotd_latedate";
                        new_qotd_latedate.Value = new CrmDateTime();
                        new_qotd_latedate.Value.Value = ApplyUserDT.Rows[i]["Latedate"].ToString();
                        CreateEntity.Properties.Add(new_qotd_latedate);
                    }

                    //说明
                    if (string.IsNullOrEmpty(ApplyUserDT.Rows[i]["Detail"].ToString()) == false)
                    {
                        StringProperty new_qotd_detail = new StringProperty();
                        new_qotd_detail.Name = "new_qotd_detail";
                        new_qotd_detail.Value = ApplyUserDT.Rows[i]["Detail"].ToString();
                        CreateEntity.Properties.Add(new_qotd_detail);
                    }


                    ApplyUserDT.Rows[i]["Director"] = QotdCrmService.Create(CreateEntity);
                }
            }
            catch (SoapException ex)
            {
                throw new Exception("创建报价明细表单失败: " + ex.Detail.InnerText);
            }
        }
        //验证单价和总价
        private  bool IsNumber(string  price )
        {
            decimal num = 0;
            bool result = true;
            try
            {
                num = decimal.Parse(price);
                if (num >= decimal.MaxValue || num <= 0) {
                    result = false;
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        //验证天数
        private bool IsNumber2(string price)
        {
            int  num = 0;
            bool result = true;
            try
            {
                num = int.Parse(price);
                if (num >= 2147483647 || num <= 0)
                {
                    result = false;
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        //验证日期
        private bool IsDate(string date) {
            bool result = true;
            try
            {
                Convert.ToDateTime(date);
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

    }
}

原文地址:https://www.cnblogs.com/hellohongfu/p/2102883.html