解析excel+結合表單上的數據生成csv文件


個人網站:友書小說網(http://laiyoushu.com)綠色純淨無廣告,歡迎大家前來看小說

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Sjune.Common;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Data.SqlClient;
using NPOI.HSSF.Util;
using NPOI.HPSF;
using System.Text;
using Sjune.Model;
using System.Reflection;


namespace Sjune.Web.program.ashx
{
    /// <summary>
    /// Upload_order 的摘要說明
    /// </summary>
    public class Upload_order : Web.UI.UserPage, IHttpHandler, IRequiresSessionState
    {
        protected HSSFWorkbook hssfworkbook;
        public static string path = HttpContext.Current.Request.PhysicalApplicationPath;
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/json";
                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                context.Response.AddHeader("pragma", "no-cache");
                context.Response.AddHeader("cache-control", "");
                context.Response.CacheControl = "no-cache";
                var logName = Session["loginName"];
                string action = context.Request["action"] + "";
                Model.MV_Upload_order db_model = new Model.MV_Upload_order();

                List<ModelExcel> list = new List<ModelExcel>();

                //開始解析之前上傳excel中的數據
                try
                {
                    StringBuilder sbr = new StringBuilder();
                    var PreviousUrl = context.Request["url"].ToString();
                    PreviousUrl = path + PreviousUrl;
                    using (FileStream fs = File.OpenRead(PreviousUrl.ToString()))   //打開myxls.xls文件
                    {
                        HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls文件中的數據寫入wk中
                        for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中總共的表數
                        {
                            ISheet sheet = wk.GetSheetAt(i);   //讀取當前表數據
                            for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是當前表的總行數
                            {
                                IRow row = sheet.GetRow(j);  //讀取當前行數據
                                if (j > 0)
                                {
                                    if (row != null)
                                    {
                                        ModelExcel lu = new ModelExcel();
                                        lu.Sign_Code = row.GetCell(0).ToString();
                                        //lu.Special_Code = row.GetCell(1).ToString();
                                        lu.Counts = (row.GetCell(1).ToString()).ToInt();
                                        lu.Unit = row.GetCell(2).ToString() == "個" ? "E" : "C";
                                        list.Add(lu);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.ToString());
                }
                string timeDay = DateTime.Now.ToString("yyyyMMdd");
                db_model.User_Account = context.Request["User_Account"].ToString();
                db_model.Pro_Name = context.Request["Pro_Name"].ToString();
                db_model.Buyer_Name = context.Request["Buyer_Name"].ToString();
                db_model.Company = context.Request["Company"].ToString();
                db_model.Buyer_Tel = context.Request["Buyer_Tel"].ToString();
                db_model.Buyer_Email = context.Request["Buyer_Email"].ToString();
                db_model.Upload_Cause = context.Request["Upload_Cause"].ToString();
                db_model.PO = context.Request["PO"].ToString();
                db_model.Start_Date = context.Request["Start_Date"].ToDate().ToString("yyyy-MM-dd");
                db_model.Order_Status = "1";
                db_model.Order_Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                db_model.U_Other_Account = context.Request["U_Other_Account"].ToString();
                db_model.is_del = 0;
                //這裏生成6位數的流水號
                db_model.SerialNumber = OrderNoHelper.OrderID;
                //生成流水號
                db_model.Web_Ord_Number = timeDay + db_model.Upload_Cause + db_model.SerialNumber.ToString();
                string[] TBBody = { db_model.Web_Ord_Number, db_model.User_Account, db_model.U_Other_Account, db_model.Order_Date.Substring(0, 10), db_model.PO.ToString(), db_model.Upload_Cause, db_model.Start_Date };
                string sNewFileName = Utils.GetRamCode();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("{\"Status\":\"");
                sb.Append("/UploadSys/" + db_model.Web_Ord_Number + ".xls");
                sb.Append("\"}");
                var url = sb.ToString();
                url = url.Substring(11);
                url = path + url.Substring(0, url.LastIndexOf("xls")) + "csv"; ;


                List<ModelCSV> csvList = new List<ModelCSV>();
                for (int j = 0; j < list.Count; j++)
                {
                    ModelCSV mcs = new ModelCSV();
                    mcs.Sign_Code = "#" + list[j].Sign_Code;
                    mcs.Counts = "#" + list[j].Counts.ToString();
                    mcs.Unit = list[j].Unit;
                    mcs.Web_Ord_Number = "#" + TBBody[0];
                    mcs.User_Account = "#" + TBBody[1];
                    mcs.U_Other_Account = "#" + TBBody[2];
                    mcs.Order_Date = TBBody[3];
                    mcs.PO = "#" + TBBody[4];
                    mcs.Upload_Cause = "#" + TBBody[5];
                    mcs.SSD = TBBody[6];
                    csvList.Add(mcs);
                }
                SaveAsCSV(url, csvList);

                var UserUrl = context.Request["url"].ToString();
                db_model.File_User_Number = UserUrl.Substring(UserUrl.LastIndexOf("/") + 1);
                db_model.File_Sys_Number = url.Substring(url.LastIndexOf("/") + 1); ;
                if (new BLL.Upload_Order().Add(db_model) > 0)
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(new { Status = 0, Message = "數據添加成功", Data = "" }));
                }
                else
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(new { Status = 1, Message = "數據添加失敗,請刷新頁面重試", Data = "" }));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        protected void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            hssfworkbook.DocumentSummaryInformation = dsi;
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "NPOI SDK Example";
            hssfworkbook.SummaryInformation = si;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //生成csv文件
        public static bool SaveAsCSV<T>(string fileName, IList<T> listModel) where T : class, new()
        {
            bool flag = false;
            try
            {
                StringBuilder sb = new StringBuilder();
                //通過反射 顯示要顯示的列
                BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射標識
                Type objType = typeof(T);
                PropertyInfo[] propInfoArr = objType.GetProperties(bf);
                string header = string.Empty;

                List<string> listPropertys = new List<string>();

                foreach (PropertyInfo info in propInfoArr)
                {
                    if (string.Compare(info.Name.ToUpper(), "ID") != 0) //不考慮自增長的id或者自動生成的guid等
                    {
                        if (!listPropertys.Contains(info.Name))
                        {
                            listPropertys.Add(info.Name);
                        }
                        header += info.Name + ",";
                    }
                }

                header = "Web Order Number" + "," + "Customer Account Number" + "," + "Customer Branch Account" + "," + "Order date" + "," + "PO Number" + "," + "Order Type" + "," + "SS Date" + "," + "Product ID(Product Identification Code)" + "," + "QTY(Quantity)" + "," + "Unit";

                sb.AppendLine(header.Trim(',')); //csv頭


                foreach (T model in listModel)
                {
                    string strModel = string.Empty;
                    foreach (string strProp in listPropertys)
                    {
                        foreach (PropertyInfo propInfo in propInfoArr)
                        {
                            if (string.Compare(propInfo.Name.ToUpper(), strProp.ToUpper()) == 0)
                            {
                                PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);
                                if (modelProperty != null)
                                {
                                    object objResult = modelProperty.GetValue(model, null);
                                    string result = ((objResult == null) ? string.Empty : objResult).ToString().Trim();
                                    if (result.IndexOf(',') != -1)
                                    {
                                        result = "\"" + result.Replace("\"", "\"\"") + "\""; //特殊字符處理 
                                        //result = result.Replace("\"", "“").Replace(',', ',') + "\"";
                                    }
                                    if (!string.IsNullOrEmpty(result))
                                    {
                                        Type valueType = modelProperty.PropertyType;
                                        if (valueType.Equals(typeof(Nullable<decimal>)))
                                        {
                                            result = decimal.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(decimal)))
                                        {
                                            result = decimal.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<double>)))
                                        {
                                            result = double.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(double)))
                                        {
                                            result = double.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<float>)))
                                        {
                                            result = float.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(float)))
                                        {
                                            result = float.Parse(result).ToString("#.#");
                                        }
                                    }
                                    strModel += result + ",";
                                }
                                else
                                {
                                    strModel += ",";
                                }
                                break;
                            }
                        }
                    }
                    strModel = strModel.Substring(0, strModel.Length - 1);
                    sb.AppendLine(strModel);
                }
                string content = sb.ToString();
                string dir = Directory.GetCurrentDirectory();
                string fullName = Path.Combine(dir, fileName);
                if (File.Exists(fullName)) File.Delete(fullName);
                using (FileStream fs = new FileStream(fullName, FileMode.CreateNew, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.Flush();
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }
                flag = true;
            }
            catch
            {
                flag = false;
            }
            return flag;

        }

        //csvmodel
        public class ModelCSV
        {
            public string Web_Ord_Number { get; set; }
            public string User_Account { get; set; }
            public string U_Other_Account { get; set; }
            public string Order_Date { get; set; }
            public string PO { get; set; }
            public string Upload_Cause { get; set; }
            public string SSD { get; set; }
            public string Sign_Code { get; set; }
            public string Counts { get; set; }
            public string Unit { get; set; }
        
        }
    }

}


如有問題,請加我QQ:631931078或352167311

發佈了37 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章