C#使用Excel导入2

 [Route("api/DataBase/ExcelImport/")]
        [HttpPost]
        public BaseResult ExcelImport()
        {
            HttpFileCollection filelist = HttpContext.Current.Request.Files;
            if (filelist != null && filelist.Count > 0)
            {
                string fileExt = string.Empty;
                string FileName = string.Empty;
                string FilePath = string.Empty;
                for (int j = 0; j < filelist.Count; j++)
                {
                    HttpPostedFile file = filelist[j];
                    FileName = file.FileName;
                    if (!FileName.Trim().ToLower().EndsWith(".xlsx") && !FileName.Trim().ToLower().EndsWith(".xls"))
                    {
                        return new BaseResult { ResCode = ResCode.Fail, ResMsg = "文件格式不正确,只能上传Excel文件" };
                    }
                    string strFileName = file.FileName.ToString();
                    fileExt = file.FileName.Substring(file.FileName.LastIndexOf(‘.‘)).ToLower();//文件后缀名
                    if (FileName != "")
                    {
                        //先上传文件到服务器固定路径
                        string dateStr = DateTime.Now.ToString("yyyyMMddHHmmssms");
                        string filename = Path.GetFileNameWithoutExtension(FileName);
                        string oldfilekz = Path.GetExtension(FileName);
                        FilePath = HostingEnvironment.MapPath("~/UploadExcel/");
                        DirectoryInfo di = new DirectoryInfo(FilePath);
                        if (!di.Exists) { di.Create(); }
                        file.SaveAs(FilePath + filename + dateStr + oldfilekz);
                        strFileName = FilePath + filename + dateStr + oldfilekz;//文件路经
                        ArrayList list = new ArrayList();
                        var dt = ExcelToTable(strFileName);
                        if (dt.Rows.Count > 0)
                        {
                            try
                            {
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    //获取订单编号
                                    string ordergoodsid = dt.Rows[i]["订单编号"].ToString();
                                    //获取快递公司
                                    string expresscompany = dt.Rows[i]["快递公司"].ToString();
                                    //获取快递单号
                                    string expressnum = dt.Rows[i]["快递单号"].ToString();
                                    StringBuilder Sql = new StringBuilder();
                                    //修改语句-发货
                                    if (!string.IsNullOrEmpty(expresscompany) && !string.IsNullOrEmpty(expressnum))
                                    {
                                        //查询是否已发货(第二次导入)
                                        string orderstate = context.ordergoods.SingleOrDefault(s => s.ordergoodsid == ordergoodsid).orderstate;
                                        if (orderstate == "1")//待发货
                                        {
                                            Sql.Append(string.Format("update ordergoods set expresscompany = ‘{0}‘,expressnum=‘{1}‘,delivergoods=‘1‘,orderstate=‘2‘,delivergoodsdate=‘{2}‘ where ordergoodsid = ‘{3}‘", expresscompany, expressnum, DateTime.Now, ordergoodsid));
                                            list.Add(Sql);
                                        }
                                    }
                                }
                                if (list.Count != 0)
                                {
                                    foreach (var item in list)
                                    {
                                        string sql = item.ToString();
                                        ExcuteSQL(item.ToString());
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                return new BaseResult { ResCode = ResCode.Fail, ResMsg = "导入Excel的格式不正确" };
                            }
                        }
                    }
                }
                return new BaseResult { ResCode = ResCode.Ok, ResMsg = "导入成功" };
            }
            else
            {
                return new BaseResult { ResCode = ResCode.Fail, ResMsg = "未选择导入的文件" };
            }
        }

        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static 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);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static 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;
            }
        }

C#使用Excel导入2

上一篇:js父级页面跳转


下一篇:Windows如何安装Apache服务