zoukankan      html  css  js  c++  java
  • 文件上传控件asp:FileUpload

    前端

    使用的控件<asp:FileUpload ID="fileup" runat="server" /><span class="message">*</span>

    $("#btn_Save_").click(function () {
    var url = "Upload.aspx?_method=import";
    // url += "&_method=import";
    form1.action = url;
    form1.submit();
    });

    后端:

    准备 操作Excel,csv等等的通用类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.OleDb;
    using System.IO;

    namespace Holworth.Utility
    {
    public class ExcelUtil
    {
    public static DataTable GetCSV(string path)
    {
    DataTable dt = new DataTable();
    bool isDtHasColumn = false; //标记DataTable 是否已经生成了列 
    StreamReader reader = new StreamReader(path, System.Text.Encoding.Default); //数据流 
    while (!reader.EndOfStream)
    {
    string message = reader.ReadLine();
    string[] splitResult = message.Split(new char[] { ',' },StringSplitOptions.None); //读取一行 以逗号分隔 存入数组 
    if (splitResult.Length <= 1)
    {
    continue;
    }
    DataRow row = dt.NewRow(); 
    if (!isDtHasColumn)
    {
    for (int i = 0; i < splitResult.Length; i++)
    {
    if (!isDtHasColumn) //如果还没有生成列 
    {
    dt.Columns.Add("column" + i, typeof(string));
    }
    }
    isDtHasColumn = true;
    continue;
    }
    isDtHasColumn = true;
    row = dt.NewRow();
    for (int i = 0; i < splitResult.Length&&i<dt.Columns.Count; i++)
    {
    row[i] = splitResult[i].Trim().Replace(""", "");
    }
    dt.Rows.Add(row); //添加行 
    }
    return dt;
    }
    public static DataTable GetExcelSheetContent(string strPath, string sheetName)
    {
    string mystring = "";
    DataTable dt = new DataTable();
    mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";
    if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
    {
    mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 12.0;HDR=YES'";
    }
    OleDbConnection connection = new OleDbConnection(mystring);
    OleDbDataAdapter da = null;
    try
    {

    da = new OleDbDataAdapter("select * from [" + sheetName + "]", connection);
    da.Fill(dt);
    return dt;
    }
    catch (OleDbException err)
    {
    throw new Exception("执行查询语句时出错:" + err.Message);
    }
    finally
    {
    connection.Close();
    da.Dispose();
    }
    }
    public static string[] GetExcelTableName(string strPath)
    {

    string mystring = "";
    mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
    if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
    {
    mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 12.0;HDR=YES'";
    }
    //IList<string> tblNames = null;
    DataTable tblSchema = null;
    string tableName = "";
    OleDbConnection connection = new OleDbConnection(mystring);
    try
    {
    if (connection.State != ConnectionState.Open)
    connection.Open();
    //Prepare the command
    tblSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    string[] mySheetName = new string[tblSchema.Rows.Count];
    int i = 0;
    foreach (DataRow row in tblSchema.Rows)
    {
    tableName = row["TABLE_NAME"].ToString();
    //tableName = tableName.Replace("'", "");
    //tableName = tableName.Replace("$", "");
    //tableName = tableName.Replace("#", ".");
    mySheetName[i] = tableName;
    i++;
    }
    return mySheetName;
    }
    catch (OleDbException err)
    {
    if (err.ErrorCode == -2147467259)
    throw new Exception("您选择的Excel文件不是预期的格式!");
    else
    throw new Exception("执行查询语句时出错:" + err.Message);
    }
    finally
    {
    connection.Close();
    }
    return null;
    }
    }
    }

    //前面为准备类ExcelUtil用户读取excel,csvd等

    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request["_method"] == "import")
    {
    Import();
    }
    }
    private void Import()
    {
    string fileName = Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xlsx");

    //把文件保存到指定的路径

    this.fileup.SaveAs(fileName);
    if (string.IsNullOrEmpty(fileup.FileName))
    {
    ScriptHelper.MessageBox(false, "请选择文件不能上传空文件",0);
    return;
    }
    //Psvc.SaveInsertMktRateMarketData(fileName, Request["drp_DataType_"] == "1", false);
    GetExcelDirectory(fileName);
    System.IO.File.Delete(fileName);
    SaveLog(string.Empty, "导入");

    //读取43张ExcelSheet 进行验证 并把数据导入到(数据库)

    ScriptHelper.MessageBox(true, "Import_Sucess", 1);

    }

    DataTable dtMulu = new DataTable();
    public void GetExcelDirectory(string fileName)
    {
    beginProgress();
    // System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
    ;
    //if (fd.ShowDialog() == DialogResult.OK)
    {
    //读取某路径下fileName下的某个ExcelSheet的内容,所有行读出来放到DataTable 里
    dtMulu = ExcelUtil.GetExcelSheetContent(fileName, "目录$");

    //获取某Excel文件下的所有DataTable的表名放到一个字符串数组中
    string[] dtAllTable = ExcelUtil.GetExcelTableName(fileName);
    HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V fc = new HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V();
    int len = dtAllTable.Length;
    int i = 1;
    double percent = 0.00f;
    Framework.QueryInfo infoDle=new Framework.QueryInfo();
    infoDle.QueryObject = "To38ImportResult";
    IList list = Dao.FindList(infoDle);
    List<To38ImportResult> list2 =new List<To38ImportResult>();
    foreach (var t in list)
    {
    list2.Add(t as To38ImportResult);

    }
    list2.ForEach(a=>a.State.MarkDeleted());
    Dao.SaveOrUpdateAll(list2);

    foreach (string item in dtAllTable)
    {


    if (!(item.LastIndexOf("属性表") > 0))
    {

    #region 反射获取验证页面所在的程序集

    Assembly asm = Assembly.GetAssembly(fc.GetType());

    #endregion

    if (item != "目录$")
    {
    if (dtAllTable.Length > 0 && dtAllTable != null)
    {
    string b;
    b = item.Replace("$", "");
    string tableEn = GetTableToEn(b);


    //Type t = asm.GetType("HraWeb.ReportEg.To38Validate.Validate.FX_FORWARD_V");
    Type t = asm.GetType(fc.GetType().Namespace + "." + tableEn.Trim() + "_V");//到时候替换成右边这个
    object o = Activator.CreateInstance(t);
    MethodInfo getSqlMethodInfo = t.GetMethod("TestImport");


    if (!string.IsNullOrEmpty(tableEn))
    {
    getSqlMethodInfo.Invoke(o, new object[] { fileName, item, b});//tableEn


    }

    }
    }

    }
    if (i == len)
    {
    percent = 1;
    setProgress((percent * 100).ToString().Split('.')[0]);
    finishProgress();
    break;


    }
    percent = i*1.0 / len ;

    setProgress((percent * 100).ToString().Split('.')[0]);
    System.Threading.Thread.Sleep(70);
    i++;
    }
    }
    }

    /* Copyright (c) 2015 Xiamen HaiHui Software Co., Ltd. All rights reserved
    * 其中某个验证类
    * Create by huanglc@holworth.com at 2015-01-15 20:25:38
    *
    */

    using System;
    using System.Text;
    using System.Web.ApplicationServices;
    using Aspose.Cells;
    using Contract.Domain;
    using Holworth.Utility;
    using HraWeb.Common;
    using HraWeb.ReportEg.To38Validate.ValidateGenericInterface;
    using HraWeb.ReportEg.To38Validate.ValidateInteface;

    namespace HraWeb.ReportEg.To38Validate.Validate
    {

    ///<summary>
    ///外汇远期属性表
    ///</summary>

    public class FX_FORWARD_OPT_V : BasePage,IGenericValidate
    {

    public void TestImport(string ExcelFileName, string ExcelTabFileNameEN,string ExcelTabFileNameCN)
    {
    int RecordCount = 0;
    To38ImportResult r=new To38ImportResult();
    r.Tname = this.GetType().Name.Substring(0, this.GetType().Name.Length - 2); //"FX_FORWARD_OPT_V";
    r.TStartTime = DateTime.Now;
    //string[] tableName = Holworth.Utility.ExcelUtil.GetExcelTableName(ExcelFileName); //@"c:1.xls"
    //System.Data.DataTable table = Holworth.Utility.ExcelUtil.GetExcelSheetContent(ExcelFileName, ExcelTabFileNameEN); //tableName[0]
    System.Data.DataTable table = ExcelUtil.GetExcelSheetContent(ExcelFileName, ExcelTabFileNameEN);
    System.Text.StringBuilder etrorSb = new StringBuilder();
    int i = 0;
    System.Collections.ArrayList list = new System.Collections.ArrayList();
    foreach (System.Data.DataRow row in table.Rows)
    {
    bool v_bool = true;
    Contract.Domain.FxForwardOpt a = new Contract.Domain.FxForwardOpt();
    string trade_id = row[0].ToString();
    //product_id,
    string notional_1 = row[1].ToString();
    string notional_2 = row[2].ToString();
    string trade_date = row[3].ToString();
    // string value_date = row[4].ToString();
    string optional_date = row[4].ToString();
    string maturity_date = row[5].ToString();
    string currency_1 = row[6].ToString();
    string currency_2 = row[7].ToString();
    string counterparty = row[8].ToString();
    string folder = row[9].ToString();
    string trader = row[10].ToString();
    //block_number


    if (string.IsNullOrEmpty(row[0].ToString()))//记录结束
    {

    break;
    }
    RecordCount++;
    if (ValidateCommon.ValidateNotNull(trade_id.ToString()))//验证自己调用
    {
    a.TradeId = trade_id;
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 1, trade_id));
    continue;

    }

    if (ValidateCommon.ValidatePrice(notional_1))//验证自己调用
    {
    a.Notional1 = Convert.ToDecimal(notional_1);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 2, notional_1));
    continue;

    }
    if (ValidateCommon.ValidatePrice(notional_2))//验证自己调用
    {
    a.Notional2 = Convert.ToDecimal(notional_2);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 3, notional_2));
    continue;

    }
    if (ValidateCommon.ValidateDateTime(trade_date))//验证自己调用
    {
    trade_date = ValidateCommon.ValidateDateTimeString(trade_date);
    a.TradeDate = Convert.ToDateTime(trade_date);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 4, trade_date));
    continue;

    }
    if (ValidateCommon.ValidateDateTime(optional_date))//验证自己调用
    {
    optional_date = ValidateCommon.ValidateDateTimeString(optional_date);
    a.OptionalDate = Convert.ToDateTime(optional_date);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 5, optional_date));
    continue;

    }

    if (ValidateCommon.ValidateDateTime(maturity_date))//验证自己调用
    {
    maturity_date = ValidateCommon.ValidateDateTimeString(maturity_date);
    a.MaturityDate = Convert.ToDateTime(maturity_date);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 6, maturity_date));
    continue;

    }

    if (ValidateCommon.ValidateCurreny(currency_1))//验证自己调用
    {
    a.Currency1 = currency_1;
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 7, currency_1));
    continue;

    }
    if (ValidateCommon.ValidateCurreny(currency_2 ))//验证自己调用
    {
    a.Currency2 = currency_2;
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 8, currency_2));
    continue;

    }
    if (ValidateCommon.ValidateNotNull(counterparty))//验证自己调用
    {
    a.Counterparty =(counterparty);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 9, counterparty));
    continue;

    }
    if (ValidateCommon.ValidateNotNull(folder ))//验证自己调用
    {

    a.Folder = folder;
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 10, folder));
    continue;

    }
    if (ValidateCommon.ValidateNotNull(trader))//验证自己调用
    {

    a.Trader = (trader);
    }
    else
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行{1}列值为:{2}转换失败/r/n", i+2, 11, trader));
    continue;

    }
    if (a.ValueDate != null)
    {
    if (a.MaturityDate < a.ValueDate)
    {
    v_bool = false;
    etrorSb.Append(string.Format("表“" + ExcelTabFileNameCN + "”:第{0}行Maturity Date小于Value Date不符合业务规则/r/n", i+2, i + 1));
    continue;
    }
    }
    //验证成功后
    if(v_bool)
    list.Add(a);
    a.State.MarkNew();
    i++;
    }


    if (list.Count > 0)
    {
    Dao.SaveOrUpdateAll(list);
    }
    r.TEndTime = DateTime.Now;
    r.SucRec = list.Count;
    r.FaiRec = RecordCount - list.Count;
    if (string.IsNullOrEmpty(etrorSb.ToString()))
    {
    r.Result = "导入完成";

    }
    else
    {
    r.Result = etrorSb.ToString();
    }

    Dao.SaveOrUpdate(r);
    if (!string.IsNullOrEmpty(etrorSb.ToString()))
    {
    SaveLog(string.Empty,"ImportExcel",etrorSb.ToString());
    }

    }
    }

    }

  • 相关阅读:
    Python开发:关于__name__
    学习笔记之cocos2dx2.1.1实现修改plist文件数据,用TinyXml解析XML
    计算机相关书籍推荐(持续更新)
    【C语言】溢出的处理及大小端模式的判断
    使用 MDSD 开发安全可靠的软件
    关于 /dev/null 与 /dev/zero
    NetBeans 时事通讯(刊号 # 108 Jul 08, 2010)
    NetBeans 时事通讯(刊号 # 109 Jul 17, 2010)
    JDK1.6 Update21 下载
    类的内联函数的实现应该放在哪里
  • 原文地址:https://www.cnblogs.com/kexb/p/4562641.html
Copyright © 2011-2022 走看看