Front
Controls used <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 ();
});
Back end:
General classes for preparing operations excel,csv, etc.
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; Mark whether the DataTable has generated columns
StreamReader reader = new StreamReader (path, System.Text.Encoding.Default); Data flow
while (!reader. Endofstream)
{
String message = Reader. ReadLine ();
string[] Splitresult = message. Split (new char[] {', '},stringsplitoptions.none); Reads a row with a comma-delimited array
if (splitresult.length <= 1)
{
Continue
}
DataRow row = dt. NewRow ();
if (!isdthascolumn)
{
for (int i = 0; i < splitresult.length; i++)
{
if (!isdthascolumn)//If no columns have been generated
{
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); Adding rows
}
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 ("Error executing query statement:" + 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 ("The Excel file you selected is not the expected format!");
Else
throw new Exception ("Error executing query statement:" + err.) Message);
}
Finally
{
Connection. Close ();
}
return null;
}
}
}
Front for preparing class Excelutil user Read EXCEL,CSVD etc.
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");
Save the file to the specified path
This.fileup.SaveAs (FileName);
if (string. IsNullOrEmpty (Fileup. FileName))
{
Scripthelper.messagebox (False, "Please select file cannot upload empty file", 0);
Return
}
Psvc.saveinsertmktratemarketdata (FileName, request["drp_datatype_"] = = "1", false);
Getexceldirectory (FileName);
System.IO.File.Delete (FileName);
Savelog (String. Empty, "import");
Read 43 ExcelSheet for verification and import data into (database)
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)
{
Read the contents of one of the excelsheet under filename under a path, and all lines are read out and put in the DataTable.
Dtmulu = Excelutil.getexcelsheetcontent (fileName, "directory $");
Gets the table name of all the DataTable under an Excel file in a string array
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 ("property sheet") > 0))
{
#region Reflection Gets the assembly where the validation page resides
Assembly asm = assembly.getassembly (FC. GetType ());
#endregion
if (Item! = "Directory $")
{
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");//replace it with the right one.
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) Xiamen Haihui software Co., Ltd. All rights reserved
* One of the validation classes
* Create by [e-mail protected] 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>
FX forward Attribute table
</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 ()))//Record End
{
Break
}
recordcount++;
if (Validatecommon.validatenotnull (trade_id. ToString ()))//Verify yourself Call
{
A.tradeid = trade_id;
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 1, trade_id));
Continue
}
if (Validatecommon.validateprice (notional_1))//Verify yourself Call
{
A.notional1 = Convert.todecimal (Notional_1);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 2, notional_1));
Continue
}
if (Validatecommon.validateprice (notional_2))//Verify yourself Call
{
A.notional2 = Convert.todecimal (notional_2);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 3, notional_2));
Continue
}
if (Validatecommon.validatedatetime (trade_date))//Verify yourself Call
{
Trade_date = validatecommon.validatedatetimestring (trade_date);
A.tradedate = Convert.todatetime (trade_date);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 4, trade_date));
Continue
}
if (Validatecommon.validatedatetime (optional_date))//Verify yourself Call
{
Optional_date = validatecommon.validatedatetimestring (optional_date);
A.optionaldate = Convert.todatetime (optional_date);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 5, optional_date));
Continue
}
if (Validatecommon.validatedatetime (maturity_date))//Verify yourself Call
{
Maturity_date = validatecommon.validatedatetimestring (maturity_date);
A.maturitydate = Convert.todatetime (maturity_date);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 6, maturity_date));
Continue
}
if (Validatecommon.validatecurreny (currency_1))//Verify yourself Call
{
A.currency1 = currency_1;
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 7, currency_1));
Continue
}
if (Validatecommon.validatecurreny (currency_2))//Verify yourself Call
{
A.currency2 = currency_2;
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 8, currency_2));
Continue
}
if (Validatecommon.validatenotnull (counterparty))//Verify yourself Call
{
A.counterparty = (counterparty);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, 9, counterparty));
Continue
}
if (Validatecommon.validatenotnull (folder))//Verify yourself Call
{
A.folder = Folder;
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", i+2, Max, folder));
Continue
}
if (Validatecommon.validatenotnull (trader))//Verify yourself Call
{
A.trader = (Trader);
}
Else
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} row {1} column value: {2} conversion failed/r/n", I+2, one, trader));
Continue
}
if (a.valuedate! = null)
{
if (A.maturitydate < a.valuedate)
{
V_bool = false;
Etrorsb.append (String. Format ("table" + EXCELTABFILENAMECN + ": {0} rows maturity date less than value date not conforming to business rules/r/n", i+2, i + 1));
Continue
}
}
After successful verification
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 = "Import Complete";
}
Else
{
R.result = Etrorsb.tostring ();
}
Dao.saveorupdate (R);
if (!string. IsNullOrEmpty (Etrorsb.tostring ()))
{
Savelog (String. Empty, "Importexcel", etrorsb.tostring ());
}
}
}
}
File Upload Control Asp:fileupload