文件上传控件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());
}
}
}
}
文件上传控件asp:FileUpload的更多相关文章
- Web大文件上传控件-asp.net-bug修复-Xproer.HttpUploader6.2
版权所有 2009-2016荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/in ...
- 对FileUpload文件上传控件的一些使用方法说明
//创建时间:2014-03-12 //创建人:幽林孤狼 //说明:FileUpload文件上传控件使用说明(只是部分)已共享学习为主 //可以上传图片,txt文档.doc,wps,还有音频文件,视屏 ...
- jquery文件上传控件 Uploadify 问题记录
Uploadify v3.2.1 首先引用下面的文件 <!--上传控件 uploadify--> <script type="text/javascript" s ...
- 因用了NeatUpload大文件上传控件而导致Nonfile portion > 4194304 bytes错误的解决方法
今天遇到一个问题,就是“NeatUpload大文件上传控件而导致Nonfile portion > 4194304 bytes错误”,百度后发现了一个解决方法,跟大家分享下: NeatUploa ...
- jquery文件上传控件 Uploadify
(转自 http://www.cnblogs.com/mofish/archive/2012/11/30/2796698.html) 基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同 ...
- 使用Uploadify(UploadiFive)多文件上传控件遇到的坑
最近项目中需要实现多文件上传功能,于是结合需求最终选择了Uploadify这一款控件来实现.相比其他控件,Uploadify具有简洁的界面,功能API基本可以解决大多数需求,又是基于jquery的,配 ...
- 在WebBrowser中通过模拟键盘鼠标操控网页中的文件上传控件(转)
引言 这两天沉迷了Google SketchUp,刚刚玩够,一时兴起,研究了一下WebBrowser. 我在<WebBrowser控件使用技巧分享>一文中曾谈到过“我现在可以通过WebBr ...
- ***文件上传控件bootstrap-fileinput的使用和参数配置说明
特别注意: 引入所需文件后页面刷新查看样式奇怪,浏览器提示错误等,可能是因为js.css文件的引用顺序问题,zh.js需要在fileinput.js后面引入.bootstrap最好在filein ...
- 符合BME风格的弹窗\菜单\表格\文件上传控件
1.弹窗 2.菜单 3.表格 4.文件上传控件 笔记补充......
随机推荐
- 雅虎CSS初始化代码
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,b ...
- Jquery 监听浏览器前进后退
jQuery(document).ready(function () { if (window.history && window.history.pushState) { $(win ...
- 操作系统-百科:Linux
ylbtech-操作系统-百科:Linux Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和UNIX的多用户.多任务.支持多线程和多CPU的操作系统.它能运行主要的UNI ...
- windows python文件拷贝到linux上执行问题-换行符问题/r/n
之前在Windows下写好了一个Python脚本,运行没问题,今天在Linux下,脚本开头的注释行已经指明了解释器的路径,也用chmod给了执行权限,但就是不能直接运行脚本. 1 问题1: 报错:: ...
- Socket通讯介绍
综上原理,代码的实施的步骤如下: Socket Families(地址簇)的三种类型,这个时候是网络层 socket.AF_UNIX unix本机进程间通信 本机之间的不同进程通讯默认是不可以通讯的, ...
- web项目中遇到的Maven包依赖冲突问题解决
在搭建web项目时,出现一个比较诡异的问题,任何JSP页面突然都不能够正常地显示,系统爆出HTTP:500(服务器内部错误)的页面 HTTP Status 500 - java.lang.No ...
- verilog 之数字电路 寄存器,触发器。
我一直听说没有由code到circuit就只是入门了.实在没办法了.我想了一招,一个一个的写,然后看RTL,然后分析.这是第一篇. 1.触发器. 没有复位,置位.posedge clk 是触发沿时钟. ...
- Java 定义常量
转自:http://www.softservice.org.cn/html/zjbk/2012-8/7685.html 方法一采用接口(Interface)的中变量默认为static final的特性 ...
- java 等额本金与等额本息
等额本金与等额本息 等本等息的意思是,每月的本金相等,利息也相等. 等额本息的意思是,每月的本金+利息之和相等(其实每个月本金和利息都有变化,并不相等) 等本等息的意思是,每月的本金相等,利息不等. ...
- Tkinter tkMessageBox
Tkinter tkMessageBox: tkMessageBox模块用于显示在您的应用程序的消息框.此模块提供了一个功能,您可以用它来显示适当的消息 tkMessageBox模块 ...