using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Club365Web.BaseClass;
using Club365.Common;
using Club365.Business;
using Club365.DataLinq;
using System.Globalization;
using Microsoft.Office.Interop.Excel;
using Microsoft.Reporting.WebForms;
using System.Data;
using System.Xml;

namespace Club365Web.Member
{
public partial class MemberImport : PageBase
{
/// <summary>
/// On PreInit page event
/// </summary>
/// <param name="e"></param>
protected override void OnPreInit(EventArgs e)
{
AuthenticationRequired = true;
base.OnPreInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDowns();
}
}

/// <summary>
/// Binds the drop downs.
/// </summary>
protected void BindDropDowns()
{
//get exclude fields
string fields = System.Configuration.ConfigurationManager.AppSettings["FieldsExcludeFromMemberexport"];
string[] excludeFields = fields.Split(',');

MemberManager objMemberManager;
try
{
ddlFields.Items.Clear();
objMemberManager = new MemberManager();
IEnumerable<string> columns = objMemberManager.GetColumnNameFromTable("persons");
foreach (string c in columns)
{
if (!excludeFields.Contains(c))
{
ListItem item = new ListItem(c, c);
ddlFields.Items.Add(item);
}
}
}
catch (Exception ex)
{
// Error logging
WriteSystemLog(AppConstant.EXCEPTION + ex.Message, Convert.ToChar(AppEnum.LogType.E.ToString()));
throw ex;
}
finally
{
objMemberManager = null;
}
}

protected void btnImport_Click(object sender, EventArgs e)
{
MemberManager objMemberManager;
try
{
string ddlField = Request["ctl00$ContentPlaceHolder1$ddlFields"];
string[] ddlFields = ddlField.Split(',');

if (CurrentSession.SiteID != 0)
{
objMemberManager = new MemberManager();

System.Data.DataTable dt = (System.Data.DataTable)Session["Exceltable"];
int columns = dt.Columns.Count;
for (int i = 0; i < columns; i++)
{
dt.Columns[i].ColumnName = ddlFields[i];
}

bool isNotAllowNullFieldExist = true;

string allowFieldNotExsitErrorMessage = "";
if (!dt.Columns.Contains("PERSONID"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele PERSONID not allow null"+",";
}
if (!dt.Columns.Contains("MEMBERTYPE"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele MEMBERTYPE not allow null" + ",";
}
if (!dt.Columns.Contains("MEMBERSTATUS"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele MEMBERSTATUS not allow null" + ",";
}
//check column that not allow null exsit
if (isNotAllowNullFieldExist)
{
int rows = dt.Rows.Count;
string fields = "siteid,SENDEINVOICE,";
if (!string.IsNullOrEmpty(ddlField))
{
fields += ddlField;
}

int notImportRows = 0;
string errorNo = "";
for (int i = 0; i < rows; i++)
{
string values = CurrentSession.SiteID.ToString() + "," + "0" + ",";
for (int j = 0; j < columns; j++)
{
if (dt.Columns[j].DataType.Name=="String")
{
values += "'" + dt.Rows[i][j].ToString()+"'"+",";
}
else
{
values += dt.Rows[i][j].ToString() + ",";
}

}

//prime key check
int personId = Convert.ToInt32(dt.Rows[i]["PERSONID"]);
var isPrimeKeyExsit = objMemberManager.IsPrimeKeyExisted(CurrentSession.SiteID, personId);
if (isPrimeKeyExsit)
{
notImportRows += 1;
errorNo += (i+1).ToString() + ",";
this.lbMessage.Text += string.Format("This personID has already exsited line {0}", i) +
",";
}
else
{
//check column name FIRSTNAME,LASTNAME,DATEOFBIRTH all exsit and it's value all exsit
if (ddlField.IndexOf("FIRSTNAME") != -1 && ddlField.IndexOf("LASTNAME") != -1 &&
ddlField.IndexOf("DATEOFBIRTH") != -1 && !(dt.Rows[i]["FIRSTNAME"] is System.DBNull) && !(dt.Rows[i]["LASTNAME"] is System.DBNull) && !(dt.Rows[i]["DATEOFBIRTH"] is System.DBNull) )
{
//if alread exsit and check box ticked, then update this item
if (objMemberManager.IsPersonExisted(dt.Rows[i]["FIRSTNAME"].ToString(),
dt.Rows[i]["LASTNAME"].ToString(),
Convert.ToDateTime(
dt.Rows[i]["DATEOFBIRTH"]))==1 && cbValidate.Checked)
{
//TODO: update item
//if (!objMemberManager.UpdatePersonInfo(fields,values,CurrentSession.SiteID,personId))
//{
// notImportRows += 1;
// errorNo += (i + 1).ToString() + ",";
//}
}
else
{
//import data
if (!objMemberManager.ImportDataIntoDatabase(fields, values.TrimEnd(',')))
{
notImportRows += 1;
errorNo += (i + 1).ToString() + ",";
}
}
}
else
{
//import data
if (!objMemberManager.ImportDataIntoDatabase(fields, values.TrimEnd(',')))
{
notImportRows += 1;
errorNo += (i + 1).ToString() + ",";
}
}

}
}

if (notImportRows > 0)
{
this.lbMessage.Text = notImportRows + " lines import failed, please check line: " +
errorNo.TrimEnd(',');
}
else
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message",
"<script language='javascript' defer>alert('Import succeed!');window.location='/Member/MemberImport.aspx'</script>");
}
}
else
{
this.lbMessage.Text = isNotAllowNullFieldExist.ToString().TrimEnd(',');
}
}
else
{
this.lbMessage.Text = "SiteID lost, please login in again.";
}
}
catch (Exception ex)
{
// Error logging
WriteSystemLog(AppConstant.EXCEPTION + ex.Message, Convert.ToChar(AppEnum.LogType.E.ToString()));
throw ex;
}
finally
{
objMemberManager = null;
}

}

protected void btnUpload_Click(object sender, EventArgs e)
{
ExcelUpload();
}

/// <summary>
/// upload file
/// </summary>
protected void ExcelUpload()
{
String filepath = "";
string fileExtName = "";
string mFileName = "";
string mPath = "";

if (fu_excel.PostedFile.FileName != "")
{
filepath = fu_excel.PostedFile.FileName;
fileExtName = filepath.Substring(filepath.LastIndexOf(".") + 1);
mPath = this.Request.PhysicalApplicationPath + "UpLoadFiles\\";
mFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1);
if (!Directory.Exists(mPath))
{
try
{
Directory.CreateDirectory(mPath);
}
catch (Exception ex)
{
throw ex;
}
}
if (File.Exists(mPath + mFileName))
{
try
{
File.Delete(mPath + mFileName);
}
catch (Exception ex)
{
throw ex;
}
}

#region get file extension name

Boolean fileOK = false;
String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower();
if (fu_excel.HasFile)
{

//String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower();

String[] allowedExtensions = { ".xls",".xml" };

for (int i = 0; i < allowedExtensions.Length; i++)
{

if (fileExtension == allowedExtensions[i])
{

fileOK = true;

}

}

}
#endregion

#region Is file upload succeed?

bool fileUpOK = false;
if (fileOK)
{
try
{
fu_excel.PostedFile.SaveAs(mPath + mFileName);

fileUpOK = true;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
this.lbMessage.Text = "Upload file format error, should be. Xls or .Xml format";
}
#endregion

#region Excel will fill the dataset

if (fileUpOK)
{
System.Data.DataTable dt_User = new System.Data.DataTable();

try
{
if (fileExtension == ".xls")
{
dt_User = GetList(mPath + mFileName);
}
else if (fileExtension == ".xml")
{
dt_User = CXmlToDataTable(mPath + mFileName);
}

if (dt_User == null)
{
return;
}
}
catch (Exception ex)
{
throw ex;
}
int rowNum = 0;
try
{
rowNum = dt_User.Rows.Count;
}
catch (Exception ex)
{
throw ex;
}
if (rowNum == 0)
{
this.lbMessage.Text = "Excel table is empty, no data";
}
else
{
this.Panel1.Visible = false;
this.Panel2.Visible = true;

Session["Exceltable"] = dt_User;

string fields = "";
foreach (DataColumn dc in dt_User.Columns)
{
fields += dc.ColumnName + ",";
}
Session["fields"] = fields.TrimEnd(',');
}

}

#endregion
}
}

#region Get data from excel

/// <summary>
/// Gets the list.
/// </summary>
/// <param name="FilePath">The file path.</param>
/// <returns></returns>
public System.Data.DataTable GetList(string FilePath)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;";
string strSql = string.Empty;

Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Add(Type.Missing); ;
Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1);

string workSheetName = string.Empty;
if (!File.Exists(FilePath))
{
this.lbMessage.Text = "Excel file specified path does not exist!";
}

Workbook tmpworkBook;
Worksheet tmpworkSheet;
try
{
object missing = System.Reflection.Missing.Value;
//open a WorkBook
tmpworkBook = app.Workbooks.Open(FilePath,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing);
// tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 );
app.Visible = false;
tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1];
workSheetName = tmpworkSheet.Name;

if (workSheetName != "")
{
strSql = "select * from [" + workSheetName + "$]";

OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbDataAdapter myCommand = null;
myCommand = new OleDbDataAdapter(strSql, connectionString);
System.Data.DataTable dt = new System.Data.DataTable();
myCommand.Fill(dt);
conn.Close();
conn.Dispose();
return dt;
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
throw ex;
}
finally
{
Kill(app); //kill Excel process
}

}

public string Get_FistWorkBookName(string fileName)
{
Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Add(Type.Missing); ;
Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1);

string rev = string.Empty;
if (!File.Exists(fileName))
{
this.lbMessage.Text = "Excel file specified path does not exist!";
}

Workbook tmpworkBook;
Worksheet tmpworkSheet;
try
{
object missing = System.Reflection.Missing.Value;
//open a WorkBook
tmpworkBook = app.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing);
// tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 );
app.Visible = false;
tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1];
rev = tmpworkSheet.Name;
}
catch (Exception ex)
{
rev = "";
throw ex;
}
finally
{
tmpworkSheet = null;
tmpworkBook = null;
this.Dispose();
}
return rev;
}

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

public void Kill(Application excel)
{
IntPtr t = new IntPtr(excel.Hwnd);

int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();

}
#endregion

#region Get data from xml

public DataSet CXmlFileToDataSet(string xmlFilePath)
{
if (!string.IsNullOrEmpty(xmlFilePath))
{
string path = xmlFilePath;
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
XmlDocument xmldoc = new XmlDocument();
//根据地址加载Xml文件
xmldoc.Load(path);

DataSet ds = new DataSet();
//读取文件中的字符流
StrStream = new StringReader(xmldoc.InnerXml);
//获取StrStream中的数据
Xmlrdr = new XmlTextReader(StrStream);
//ds获取Xmlrdr中的数据
ds.ReadXml(Xmlrdr);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
//释放资源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
else
{
return null;
}
}

public System.Data.DataTable CXmlToDataTable(string xmlFilePath)
{
return CXmlFileToDataSet(xmlFilePath).Tables[0];
}

#endregion

}
}

Excel和XML文件导入的更多相关文章

  1. 如何将XML文件导入Excel中

    如下图所示为一个规范的XML文件,在Excel中可以将规范的XML文件导入到Excel成为规范的表格.具体有如下几种方法:   工具/原料   Excel 方法/步骤     单击“数据”选项卡下的“ ...

  2. 工作小结:xml文件导入到oracle

    上周遇到xml文件导入到oracle数据库中,发现正常的xml转成excle格式导入,只针对于1m以下的xml文件.当xml文件太大的时候,就没有作用了. 这时候,我找到了两种办法,一个是java,一 ...

  3. 【DRP】採用dom4j完毕XML文件导入数据库

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/lantingxv_jing/article/details/37762523     xml文件在如 ...

  4. 将CSV格式或者EXCEL格式的文件导入到HIVE数据仓库中

    学习内容:数据导入,要求将CSV格式或者EXCEL格式的文件导入到HIVE数据仓库中: ①hive建表:test1 create table test1 (InvoiceNo String, Stoc ...

  5. Laravel Excel 实现 Excel-CSV 文件导入导出功能

    Laravel Excel 是一款基于 PHPExcel 开发的Laravel框架专用的 Excel/CSV 文件导入导出功能的扩展包,用起来的非常方便. 它的 Github 地址是:https:// ...

  6. Excel关联xml文件

    1.新建没传值的xml文件,变量名称自己定义好 2.打开excel,如果之前没有设置过,点击选项 如果当前Excel菜单栏中没有开发工具项,在自定义功能区先勾选上开发选项 3.点右下角的xml映射 弹 ...

  7. SpringIOC注入模块中xml文件导入其他xml文件配置

    如果我们在spring框架中配置了多个xml文件,我们可以在读取配置文件的时候把这些xml文件一下全都读取 也可以只读一个总的xml文件,在这个总的xml文件中把其他的xml全都都导入进来. 例如: ...

  8. vcf格式文件转化为Excel(csv)格式文件(R语言的write.csv,write.table功能,Excel表的文件导入功能)

    最近在整理文件,准备把vcf文件转化为Excel格式,或者CSV格式,网上搜了一堆资料,还真有人专门开发出转化格式的工具:叫vcf2csv(下载地址http://vcf2csv.sourceforge ...

  9. pom.xml文件导入了坐标,也没有报错,为什么还是没有相关的jar包的?

    为什么会出现这样的错误呢?仔细想了想,赶紧去本地仓库看看jar也没有导入进来 解决问题的思路,就是把假的jar包文件删除掉,然后在IDEA上的坐标复制删除粘贴,IDEA就会重新导入jar包,这时就成功 ...

随机推荐

  1. JavaScript使用技巧

    使用!!操作符转换布尔值 有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回true值.为了做这样的验证,我们可以使用!!操作符来实现是非常的方便与简单.对于变量可以使用 ...

  2. JS 浮点型数字运算(转)

    示例: var num1=3.3; var num2=7.17; var ret=parseFloat(num1)+parseFloat(num2); //ret的值为:10.469999999999 ...

  3. java_UML:继承/泛化、实现、依赖、关联、聚合、组合的联系与区别 (2016-07-12)

    分别介绍这几种关系: UML关系:继承(泛化).实现.依赖.关联.聚合.组合的联系与区别 一.表示符号上的区别 二.具体区别与联系 1. 继承/泛化(Generalization) [泛化关系]:是一 ...

  4. C++类继承内存布局(三)

    参考:http://blog.csdn.net/jiangyi711/article/details/4890889# (三)成员函数 类X中每一个非静态成员函数都会接受一个特殊的隐藏参数——this ...

  5. starling 中的 EventDispatcher 和 Flash中原生的 EventDispatcher

    starling 比较早之前就有开始解了,但只到最近参与一个用starling 做为框架的手游项目才真正做为一程来使用它. 项目也是刚开始搭建,在这做些笔记. 在写一个管理类时, 遇到 starlin ...

  6. android studio 自动序列化类插件

    https://github.com/mcharmas/android-parcelable-intellij-plugin

  7. [DevExpress][TreeList]节点互斥

    关键代码: /// <summary> /// 节点互斥同步 /// 说明 /// eg: ///TreeListNode _node = e.Node; ///_node.SyncMut ...

  8. HTML5学习笔记----html5与传统html区别

    一. HTML5语法的改变 该知识点所说变化指的是基于HTML4基础上所定义的改变,主要有如下: HTML5的文件扩展符(.html或.htm)与内容类型(text/html)保持不变. HTML5中 ...

  9. sass中 混合宏 VS 继承 VS 占位符 各自的使用时机和特点

    初学者都常常纠结于这个问题“什么时候用混合宏,什么时候用继承,什么时候使用占位符?”其实他们各有各的优点与缺点,先来看看他们使用效果: a) Sass 中的混合宏使用 举例代码见 2-24 行 编译出 ...

  10. c#中struct和class的区别 z

    1.struct 是值类型,class是对象类型 2.struct 不能被继承,class可以被继承 3.struct 默认的访问权限是public,而class默认的访问权限是private. 4. ...