天天看点

通用Excel导入设计

摘要:有时候我们的数据存放在excel中(特别是对于用户来说更喜欢使用excel收集一些常用数据),而系统又需要这些数据来处理其他业务,那么此时我们就需要将这些数据导入到数据库中。但是鉴于excel的样式多种多样,因此每次导入时都必须书写很多重复的代码。很明显对于一个软件开发者做这些重复劳动是一件很无趣的事情。那么怎样来寻中一种通用的方法呢?今天我们就一块看一下如何来解决这个问题。

主要内容

excel操作组件的选择

总体设计思路

配置文件设计

类设计

编码实现

一点补充

简单的测试

总结

在开始今天的主题之前我们先简单的看一个基础的问题,那就是如何进行excel的读写。关于excel的读写操作目前主要分为:1.oledb数据库连接方式2.使用excel.exe com组件3.使用第三方控件。具体哪种方式好我们要依据具体情况而定,对于第一种方式则要求excel表格必须是想数据库中的表一样规范,例如如果excel牵扯到合并单元格的情况就很难处理了。对于第二种方式则要求用户必须按照excel,而且其效率比较低。考虑到我们的需求,所以这里选择第三种方式来操作excel。操作excel的第三方控件比较多,常见的如npoi、myxls、aspose.cells等。前两者都是开源的,并且npoi除了写excel功能比较强之外对于excel读取也是十分优秀(myxls读取excel不如npoi)。aspose.cells是一款商业控件,其操作方便性当然也是十分强大的,而且aspose是一个系列组件,不仅有操作excel的组件还有关于word、ppt、pdf、flash等操作组件。这里因为项目开发中使用的是aspose.cells,因此下面的例子中我们就拿aspose.cells来进行excel操作(大家可以去找破解版或者使用npoi,当然也可以用myxls等)。

我们去设计通用excel的目的就是为了避免重复工作,也就是说不必因为excel的样式、数据等变化而重新从零做起、重复劳动。因此我们就必须抽取一个通用的东西出来,使用时只需要关注相关的业务而不必过度关注相关excel操作和存储。再简单一点就是封装共同点,暴漏个性点。考虑到这种情况,我们可以使用配置文件的方式来解决这个问题。在配置文件中我们配置excle要导入的表、字段等信息,在进行导入时再依据配置文件将数据导入到数据库中。这样一来,在需要进行excel导入时只需要为某个或多个excel配置一个xml文件,然后调用相关的类就可以完成整个excel导入工作了。

补充:通用的局限性

在这里说明一下,虽然我们设计的是一个通用的excel导入程序,但是这里的"通用"只是相对来说的,并不是考虑了所有excel的情况,因为excel的设计情况十分的复杂多样,要将所有的情况都考虑进去是一个漫长的过程。我们这里的程序只考虑对于单sheet导入一个或多个表中的情况,并且不考虑包含统计行的情况(可以包含合并行、代码表字段等)。

既然考虑使用xml配置的方式来设计通用excel导入,因此如何设计好xml也就成了设计的重点。对于单表导入(一个excel主要导入到一个数据库表中,当然这并不排除牵扯其他代码表的情况)我们的配置文件无论以数据库为基础设计(主要是依据数据库表结构)还是以excel(主要是依据excel格式设计)为基础设计都可以,但是如果是多表导入(也就是一个excel可以导入到几张表中的情况)的话考虑其复杂性还是以数据库为基础更为合适。因此考虑到这种情况,我们整个配置设计会以数据库表结构为基础来设计。最终我们的设计样例如下:

通用Excel导入设计
通用Excel导入设计

<?xml version="1.0" encoding="utf-8" ?>

<config endtag="rowblank" headerindex="" dataindex="">

<table name="" deleterepeat="true" excludedcolumns="" >

<column isprimarykey="" columnname="" headertext="" required="true" datatype="number" datalength="100" defaultvalue="" comment="">

<codetalbe name="" primarykey="" referencecolumn="" condition=""></codetalbe>

</column>

</table>

</config>

通用Excel导入设计

在最外层为config节点,代表整个配置。其属性endtag(数据读取的结束标志,例如"rowblank"代表空行结束,在读取excel时遇到某行没有任何数据的情况则视为结束;也可以为某个列地址,在导入时到了此列就会结束导入操作);属性headerindex代表excel表头对应的行值(从1开始);dataindex表示数据列起始行索引(从1开始)。

接着是table节点,对应数据库中的表,可以有多个。其name属性对应要导入的表名称;deleterepeat属性表示是否删除重复行(如果为true则会根据主键先删除重复行再执行插入操作);excludedcolumns表示排除列,多个列名使用","分割(这些字段不会导入)。

table节点内当然就是column节点,也就是对应的列,通常有多个(注意对于excel中没有的列,而数据库表需要导入的,也需要配置column节点,此时headertext为空或不配置headertext属性)。isprimarykey属性表示是否为主键(当table节点配置deleterepeat为ture时必须指定一个column节点的isprimarykey为true,因为此属性是为了delete条件做准备的[有可能它不是真正的主键]);columnname表示对应的列名;headertext表示对应的excel列头(在依据excel别名导入时根据此值确定导入的列);required指定此列是否为必须导入的列(如果配置为true,excel中此列为空并且没有配置默认值的话则会抛出异常);datatype为数据类型(例如string、number,用于数据校验);defaultvalue为默认值(注意其值不一定是指定的字符值,可以是"max"、"newid".如果为max,那么此列必须为数值类型,此时在导入的时候如果需要使用默认值,就会在原来数据库表中此列最大值的基础上加上1导入到数据库中,如果为newid在导入的时候如果需要使用默认值系统就会自动创建id);comment是此列的说明。

在column节点中还可以配置codetable节点,表示代码表。name属性值主表的表名称;primarykey指主表的主键,也就是字表的外键;referencecolumn表示对应代码字段关联名称列,也就是我们导入时所依据的excel对应值(例如categoryid对应categoryname,那么referencecolumn就是categoryname,因为往往excel中可能存放的是类似于categoryname的东西而不是categoryid,而导入操作时需要categoryid)。

我们有了思路之后,接下来就来看一下类的设计吧。

通用Excel导入设计

在这些类中excel类是整个导入的核心,其最初要的方法就是import(),当然除此之外所有对于excel的读取和对数数据库的操作以及对配置对象的解析都是由此类负责;config类是对整个配置的抽象,其对应的方法图中也已经标出,每个config类对应多个实体类;entity是对于表的抽象,就是表对应的实体类;property类是对于列的抽象,每个entity中包含多个property;另外dictionaryentity是数据字典,是对代码表的抽象,每个property可以对应一个代码表;除此之外confighelper是对于应用程序配置的封装;asposecell是对aspose.cells的封装,包含常用的excel读写方法。

接下来我们就开始实现整个设计吧,相信有了上面的说明和代码中的注释,理解起来应该很简单的,我就不再过多赘余了。

asposecell类

通用Excel导入设计
通用Excel导入设计

using system;

using system.collections.generic;

using system.text;

using aspose.cells;

namespace cmj.dataexchange

{

//aspose帮助类,对常用aspose用法进行封装

public class asposecell

private workbook _workbook = null;

private dictionary<string,worksheet> _worksheets = null;

private worksheet _currentworksheet = null;

public asposecell(string fullname)

_workbook = new workbook();

_workbook.open(fullname);

_worksheets = new dictionary<string, worksheet>();

foreach (worksheet worksheet in _workbook.worksheets)

_worksheets.add(worksheet.name, worksheet);

}

_currentworksheet = _workbook.worksheets[0];

//设置指定名称的sheet为当前操作sheet

public void setcurrentworksheet(string worksheetname)

if (_worksheets.containskey(worksheetname))

_currentworksheet = _worksheets[worksheetname];

else

throw new exception("当前工作薄不存在\""+worksheetname+"\"工作表!");

//设置指定索引(从0开始)的sheet为当前操作sheet

public void setcurrentworksheet(byte worksheetindex)

if (worksheetindex <= _worksheets.count)

_currentworksheet = getworksheetbyindex(worksheetindex);

throw new exception("工作表索引范围超过了总工作表数量!");

//根据索引得到sheet

public worksheet getworksheetbyindex(byte index)

byte i = 0;

worksheet worksheet = null;

foreach(string name in _worksheets.keys)

if (index == i)

worksheet = _worksheets[name];

i++;

return worksheet;

//根据sheet名称得到sheet

public worksheet getworksheetbyname(string sheetname)

if (_worksheets.containskey(sheetname))

return _worksheets[sheetname];

return null;

/// <summary>

/// 判断指定行是否有数据

/// </summary>

/// <param name="row">从1开始,为excel行序号</param>

/// <returns></returns>

public bool rowhasvalue(int row)//指定行是否有数据(以连续50列没有数据为标准)

bool r = false;

for (int i = 0; i < 50; ++i)

if (_currentworksheet.cells[row - 1, i].value != null && _currentworksheet.cells[row - 1, i].value.tostring() != "")

r = true;

break;

return r;

public bool rowhasvalue(string position)//指定行是否有数据(以连续50列没有数据为标准)

if (getcellvalue(position)!="")

//取得指定sheet中指定cell位置的数据

public string getcellvalue(string worksheetname, string cellname)

return _worksheets[worksheetname].cells[cellname].value != null ? _worksheets[worksheetname].cells[cellname].value.tostring() : "";

public string getcellvalue(byte worksheetindex, string cellname)

return getworksheetbyindex(worksheetindex).cells[cellname].value != null ? getworksheetbyindex(worksheetindex).cells[cellname].value.tostring() : "";

public string getcellvalue(string cellname)

return _currentworksheet.cells[cellname].value != null ? _currentworksheet.cells[cellname].value.tostring() : "";

/// 根据行列索引得到指定位置的数据

/// <param name="row">从0开始</param>

/// <param name="column">从0开始</param>

public string getcellvalue(int row, int column)

return _currentworksheet.cells[row, column].value != null ? _currentworksheet.cells[row, column].value.tostring() : "";

/// 判断某位置的单元格是否为合并单元格

public bool ismerged(int row,int column)

return _currentworksheet.cells[row, column].ismerged;

//取得合并单元格的数据

public string getmergedcellvalue(int row, int column)//事实上合并单元格只有第一个单元格有值其他的全为空,但是我们知道其实从意义上理解合并单元格除了第一个单元格外其他单元格的值同第一个,因此这里提供这样一个方法

string r = "";

int t=row-1;

if (ismerged(row, column))

if (getcellvalue(row, column) != "")

r = getcellvalue(row, column);

else//约定合并单元格只是合并行并不和并列,并且合并行数最多50

while (t >= 0 && (row-t)<50)

if (getcellvalue(t, column) != "")

r = getcellvalue(t, column);

t--;

//取得range名称集合

public list<string> getrangenames()

list<string> names = new list<string>();

foreach (range r in _workbook.worksheets.getnamedranges())

names.add(r.name);

return names;

//取得某行range名称集合

public list<string> getrangenames(int rowindex)

if (_workbook.worksheets.getnamedranges()!=null)

if (r.firstrow == rowindex && r.worksheet == _currentworksheet)

//根据range(别名)取得行索引

public int getrowindexbyrangename(string rangename)//只返回第一行索引(从0开始)

if (_workbook.worksheets.getrangebyname(rangename) != null)

return _workbook.worksheets.getrangebyname(rangename).firstrow;

throw new exception("未有找到指定名称的单元格!");

//根据range(别名)取得列索引

public int getcolumnindexbyrangename(string rangename)//只返回第一行索引(从0开始)

return _workbook.worksheets.getrangebyname(rangename).firstcolumn;

//根据range(别名)取得行列索引

public int[] getrowandcolumnindexbyrangename(string rangename)

int[] i = new int[2];

i[0] = _workbook.worksheets.getrangebyname(rangename).firstrow;

i[1]=_workbook.worksheets.getrangebyname(rangename).firstcolumn;

return i;

通用Excel导入设计

confighelper类

通用Excel导入设计
通用Excel导入设计

using system.configuration;

//配置辅助类,主要用于读取应用程序配置文件

internal class confighelper

private static confighelper confighelper = null;

private static object obj = new object();

private string excelpath = "";//excel文件所在路径或者其根目录(此时会将其下所有excel全部倒入)

private bool usetransaction = false;

private confighelper()

//读取excel配置路径

if (configurationmanager.appsettings["excelpath"] != null)

excelpath = configurationmanager.appsettings["excelpath"];

throw new exception("未发现excel配置路径(excelpath),请检查配置文件!");

if (configurationmanager.appsettings["usetransaction"] != null)

usetransaction = convert.toboolean(configurationmanager.appsettings["usetransaction"]);

public static confighelper instance()

lock (obj)

if (confighelper == null)

confighelper = new confighelper();

return confighelper;

public string excelpath

get

return excelpath;

set

excelpath = value;

public bool usetransaction

return usetransaction;

usetransaction = value;

通用Excel导入设计

dictionaryentity类

通用Excel导入设计
通用Excel导入设计

//代码表类,是对codetable的抽象

internal class dictionaryentity

private string name = "";//代码表名称,对应数据库中主表名称

private string primarykey = "";//代码表主键,也就是字表的对应外键

private string referencecolumn = "";//代码字段关联名称列,也就是我们导入时所依据的excel对应值

private string condition = "";//相关条件

public dictionaryentity()

public string name

return name;

name = value;

public string primarykey

return primarykey;

primarykey = value;

public string referencecolumn

return referencecolumn;

referencecolumn = value;

public string condition

return condition;

condition = value;

通用Excel导入设计

property类

通用Excel导入设计
通用Excel导入设计

//配置属性类,抽象了配置文件的配置属性,对应于数据库中的字段

internal class property

private bool isprimarykey=false;//是否为主键

private string columnname = "";//数据库列名称

private string headertext = "";//对应的excel列头名称

private bool required = true;//是否为必填字段

private string datatype = "string";//数据类型(默认为string类型)

private int datalength = 5000;//数据长度(默认为5000)

private string defaultvalue = "";//默认值(对应excel此列的值如果为空则会使用此值来导入)

private string comment = "";//字段说明信息(非必要属性)

private dictionaryentity codetalbe = null;//对应的代码表

public property()

public bool isprimarykey

return isprimarykey;

isprimarykey = value;

public string columnname

return columnname;

columnname = value;

public string headertext

return headertext;

headertext = value;

public bool required

return required;

required = value;

public string datatype

return datatype;

datatype = value;

public int datalength

return datalength;

datalength = value;

public string defaultvalue//解析过的默认值(也就是说直接就是值,而不是其地址什么的)

return defaultvalue;

defaultvalue = value;

public string comment//说明信息

return comment;

comment = value;

public dictionaryentity codetable//代码表

return codetalbe;

codetalbe = value;

通用Excel导入设计

entity类

通用Excel导入设计
通用Excel导入设计

//实体类,对配置文件中table的抽象,对应数据库中的表

internal class entity

private string name = "";//表名称

private bool deleterepeat = false;//是否删除重复(默认为false,如果设为true则在插入时首先根据主键删除重复信息)

private list<property> propertys = null;//属性集合(每个实体对应多个property)

private list<string> excludedcolumns = null;//排除字段(也就是指明哪些字段不用导入)

public entity()

propertys = new list<property>();

excludedcolumns = new list<string>();

public entity(string name)

this.name=name;

public bool deleterepeat

return deleterepeat;

deleterepeat = value;

public list<string> excludedcolumns

return excludedcolumns;

excludedcolumns = value;

public list<property> propertys

return propertys;

propertys = value;

通用Excel导入设计

config类

通用Excel导入设计
通用Excel导入设计

using system.xml;

using cmj.myfile;

//配置类,是对整个配置的抽象

internal class config

#region excel读取相关成员变量

private myxml xml = null;

#endregion

#region 配置文件相关成员变量

private string endflag = "rowblank";//excel结束标志

private byte headerindex = 1;//列头所在行

private byte dataindex = 2;//数据行起始位置

private list<entity> entities = null;//配置类对应的实体类(也就是说配置时,每个config节点中可以有多个table节点)

public config(string excelconfigfullname)

//初始化成员变量

entities = new list<entity>();

//读取配置文件,类初始化

init(excelconfigfullname);

public string endflag

return endflag;

public int headerindex

return headerindex;

public int dataindex

return dataindex;

public list<entity> entities

return entities;

//初始化配置对象

private void init(string excelconfigfullname)

int t = 1;

bool r = true;

xml = new myxml(excelconfigfullname);

endflag = xml.getsinglenodeattribute("config", "endflag") != "" ? xml.getsinglenodeattribute("config", "endflag") : "rowblank";//默认判断是否读取结束的标志设为“rowblank”,也就是空行。

r = int.tryparse(xml.getsinglenodeattribute("config", "headerindex"), out t);

if (r)

headerindex = convert.tobyte(xml.getsinglenodeattribute("config", "headerindex"));

r = int.tryparse(xml.getsinglenodeattribute("config", "dataindex"), out t);

dataindex = convert.tobyte(xml.getsinglenodeattribute("config", "dataindex"));

if (myfillebase.filebeing(excelconfigfullname))//根据完整路径判断文件是否存在

addenities(excelconfigfullname);

throw new exception("相应配置文件未找到,请检查相应文件是否存在!");

//初始化实体对象

private void addenities(string fullname)

xml = new myxml(fullname);

xmlnodelist tables = xml.getnodes("config/table");

entity entity = null;

property property = null;

bool t = true;

bool r=true;

int i = 0;

foreach (xmlnode table in tables)

entity = new entity(xml.getnodeattribute(table,"name"));

r = bool.tryparse(xml.getnodeattribute(table, "deleterepeat"),out t);

entity.deleterepeat = convert.toboolean(xml.getnodeattribute(table, "deleterepeat"));

if (xml.getfirstchildnode(table) != null)//说明有列配置

foreach (xmlnode column in xml.getchildnodes(table))

property = new property();

r = bool.tryparse(xml.getnodeattribute(column, "isprimarykey"), out t);

property.isprimarykey = convert.toboolean(xml.getnodeattribute(column, "isprimarykey"));

property.columnname = xml.getnodeattribute(column, "columnname");

if (xml.getnodeattribute(column, "headertext") != "")

property.headertext = xml.getnodeattribute(column, "headertext");

r = bool.tryparse(xml.getnodeattribute(column, "required"), out t);

property.required = convert.toboolean(xml.getnodeattribute(column, "required"));

property.datatype = xml.getnodeattribute(column, "datatype") != "" ? xml.getnodeattribute(column, "datatype") : "string";

if (xml.getnodeattribute(column, "datalength") != "")

r = int.tryparse(xml.getnodeattribute(column, "datalength"),out i);

property.datalength = i;

property.comment = xml.getnodeattribute(column, "comment");

property.defaultvalue = xml.getnodeattribute(column, "defaultvalue") != "" ? xml.getnodeattribute(column, "defaultvalue") : "";

if (xml.getfirstchildnode(column) != null)//说明有代码表

dictionaryentity dictionaryentity = new dictionaryentity();

dictionaryentity.name = xml.getnodeattribute(xml.getfirstchildnode(column), "name");

dictionaryentity.primarykey = xml.getnodeattribute(xml.getfirstchildnode(column), "primarykey");

dictionaryentity.referencecolumn = xml.getnodeattribute(xml.getfirstchildnode(column), "referencecolumn");

dictionaryentity.condition = xml.getnodeattribute(xml.getfirstchildnode(column), "condition");

property.codetable = dictionaryentity;

entity.propertys.add(property);

entities.add(entity);

string excludedcolumns = xml.getnodeattribute(table, "excludedcolumns");

if (excludedcolumns != "")

foreach (string ec in excludedcolumns.split(','))

entity.excludedcolumns.add(ec);

通用Excel导入设计

excel类

通用Excel导入设计
通用Excel导入设计

using system.data;

using cmj.mydata;

//excel导入核心类

public class excel

private dictionary<string, config> configs =null;//配置文件全路径和对应的配置类键值集合

private string excelpath="";//excel路径(可以为目录)

bool usetransaction=false;//是否使用事务

private asposecell asposecell = null;//aspose.cells封装类

private sqlhelper dbhelper = new sqlhelper();//数据库操作封装类

public excel()

excelpath=confighelper.instance().excelpath;

usetransaction = confighelper.instance().usetransaction;

initconfig();

public excel(string excelpath,bool usetransaction)

this.excelpath=excelpath;

this.usetransaction = usetransaction;

confighelper.instance().excelpath = excelpath;

confighelper.instance().usetransaction = usetransaction;

//导入操作核心方法,负责整个excel导入

public void import()

if (configs.count > 0)

if (usetransaction)//使用事务的情况

dbhelper.transationhandler(sqlhelper.transationtype.open);

excuteimport();

dbhelper.transationhandler(sqlhelper.transationtype.complete);

throw new exception("config对象个数为0,无法导入!");

//执行excel导入

private void excuteimport()

string sqldelete = "";//删除操作对应的sql语句

string sqlinsert = "";//插入操作使用的sql语句

int headerindex = 1;//列头所在行

int dataindex = 2;//数据起始行

string endflag = "rowblank";

foreach (string excelfullname in configs.keys)//遍历所有config

asposecell = new asposecell(excelfullname);

list<entity> entities = configs[excelfullname].entities;//注意每个config中不一定只有一个实体,可以配置多个,这样每个excel可以导入到多张表中

headerindex = configs[excelfullname].headerindex;

dataindex = configs[excelfullname].dataindex;

endflag = configs[excelfullname].endflag;

while (!isend(asposecell, endflag, dataindex))

foreach (entity entity in entities)

if (entity.propertys.count > 0)//说明配置了column字段

if (entity.deleterepeat)

sqldelete = "delete from " + entity.name + " where " + getsqlconditionstring(asposecell, entity, headerindex, dataindex);

dbhelper.excutenonquery(commandtype.text, sqldelete);

sqlinsert = "insert into " + entity.name + "(" + getsqlfieldstring(asposecell, entity) + ")" + " values(" + getsqlfieldvaluestring(asposecell, entity, headerindex, dataindex) + ")";

dbhelper.excutenonquery(commandtype.text, sqlinsert);

if (asposecell.getrangenames(headerindex - 1).count > 0)//说明指定了单元格别名作为列名

sqlinsert = "insert into " + entity.name + "(" + getsqlfieldstringaccordingtoalias(asposecell, headerindex) + ") values(" + getsqlfieldvaluestringaccordingtoalias(asposecell, headerindex, dataindex) + ")";

else if (entity.excludedcolumns.count > 0)//说明有排除字段

sqlinsert = "insert into " + entity.name + "(" + getsqlfieldstringaccordingtoexcludedcolumns(asposecell, entity) + ") values(" + getsqlfieldvaluestringwithoutalias(asposecell, entity, headerindex, dataindex) + ")";

sqlinsert = "insert into " + entity.name + " values(" + getsqlfieldvaluestringwithoutalias(asposecell, entity, headerindex, dataindex) + ")";

dataindex++;

/// 根据endflag标记判断当前数据行是否结束

/// <param name="asposecell"></param>

/// <param name="endflag"></param>

/// <param name="row"></param>

private bool isend(asposecell asposecell,string endflag,int row)

switch (endflag)

case "rowblank":

if (!asposecell.rowhasvalue(row))

default :

if (asposecell.getcellvalue(endflag+row.tostring()) == "")

/// 根据headertext配置节确定列索引(从0开始)

/// <param name="headerindex"></param>

/// <param name="headertext"></param>

private int getcolumnindexbyheadertext(asposecell asposecell,int headerindex,string headertext)

int columnindex=0;

int r=0;

while (asposecell.getcellvalue(headerindex-1, columnindex) != "")

if (asposecell.getcellvalue(headerindex-1, columnindex) == headertext)

r = columnindex;

columnindex++;

/// 根据defaultvalue配置节确定默认值

/// <param name="entityname"></param>

/// <param name="columnname"></param>

/// <param name="defaultvalue"></param>

private string getdefaultvalue(asposecell asposecell,string entityname,string columnname, string defaultvalue)

switch (defaultvalue)

case "newid": r = guid.newguid().tostring(); break;

case "max": r = dbhelper.executescalar(commandtype.text, "select max(" + columnname + ") from " + entityname + "") != null ?((convert.toint32(dbhelper.executescalar(commandtype.text,"select max(" + columnname + ") from " + entityname + "").tostring())+1).tostring()) : "1"; break;

default: r = defaultvalue; break;

/// 得到查询条件sql语句段

/// <param name="entity"></param>

/// <param name="dataindex"></param>

private string getsqlconditionstring(asposecell asposecell, entity entity,int headerindex,int dataindex)

string sql="";

foreach (property p in entity.propertys)

if(p.isprimarykey)

sql+=p.columnname+"=";

if (p.headertext!="")

sql+="'"+asposecell.getcellvalue(dataindex-1,getcolumnindexbyheadertext(asposecell,headerindex,p.headertext))+"'";

sql += "'"+getdefaultvalue(asposecell, entity.name, p.columnname, p.defaultvalue)+"'";

sql += " and";

sql = sql.substring(0, sql.length - 4);

return sql;

/// 得到查询字段sql语句段

private string getsqlfieldstring(asposecell asposecell,entity entity)

string sql = "";

sql += p.columnname+",";

sql = sql.trimend(',');

/// 依据别名得到查询字段sql段

private string getsqlfieldstringaccordingtoalias(asposecell asposecell,int headerindex)

foreach (string columnname in asposecell.getrangenames(headerindex - 1))

sql += columnname + ",";

/// 依据排除列得到查询字段sql语句段

private string getsqlfieldstringaccordingtoexcludedcolumns(asposecell asposecell, entity entity)

foreach(datacolumn column in dbhelper.getdatatable(commandtype.text,"select top 0 * from "+entity.name).columns)

if (!entity.excludedcolumns.contains(column.columnname))

sql += column.columnname + ",";

/// 得到查询值sql语句段

private string getsqlfieldvaluestring(asposecell asposecell, entity entity,int headerindex, int dataindex)

string v = "";

foreach (property p in entity.propertys)//遍历实体的所有属性

if (p.codetable != null)

sql += "'" + getcodetablevalue(asposecell,p,headerindex,dataindex).replace("'","''") + "',";//注意如果单元格本身的值就有“'”的情况

else//说明此属性是一个代码表字段

if(asposecell.ismerged(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, p.headertext)))//是否为合并单元格(对于合并单元格取此合并单元格的第一个值)

v=asposecell.getmergedcellvalue(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, p.headertext));

v=asposecell.getcellvalue(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, p.headertext));

if (v == "")//说明单元格中没有任何值,就要考虑“默认值”和“必须”属性

if (getdefaultvalue(asposecell, entity.name, p.columnname, p.defaultvalue) != "")//说明有默认值

v = getdefaultvalue(asposecell, entity.name, p.columnname, p.defaultvalue);

else//如果单元格没有值并且无默认值,则检查此属性是否是必须的

if (!p.required)

v = "";

throw new exception("列\""+p.headertext+"\""+"不能为空!");

//检查类型

if (p.datatype != "" && p.datatype != "string")

if (!validatedatatype(v, p.datatype))

throw new exception("列\"" + p.headertext + "\"中存在非\"" + p.datatype + "\"类型数据!");

//属性长度检查

if (p.datalength != 0 && p.datalength != 5000)

if(!validatedatalength(v,p.datalength))

throw new exception("列\"" + p.headertext + "\"中存长度超过\"" + p.datalength.tostring() + "\"的数据!");

sql += "'"+v.replace("'", "''")+"',";

//数据类型校验

private bool validatedatatype(string value,string type)

bool r=false;

double t = 0;

switch (type.tolower())

case "number":

r = double.tryparse(value, out t);

case "string": r = true;

default: break; ;

//数据长度校验

private bool validatedatalength(string value, int length)

if (value.length > length)

return false;

return true;

/// 得到查询值sql语句段(未配置列情况下使用且有别名)

private string getsqlfieldvaluestringaccordingtoalias(asposecell asposecell, int headerindex, int dataindex)//对于没有配置列的情况使用

if(asposecell.ismerged(dataindex - 1,asposecell.getcolumnindexbyrangename(columnname)))

sql+="'"+asposecell.getmergedcellvalue(dataindex - 1, asposecell.getcolumnindexbyrangename(columnname)).replace("'","''")+"',";

sql += "'" + asposecell.getcellvalue(dataindex - 1, asposecell.getcolumnindexbyrangename(columnname)).replace("'", "''") + "',";

/// 得到查询值sql语句段(未配置列情况下使用且无别名,不管有没有排除字段)

private string getsqlfieldvaluestringwithoutalias(asposecell asposecell,entity entity, int headerindex, int dataindex)//对于没有配置列的情况使用

int column = 0;

while (asposecell.getcellvalue(headerindex-1, column) != "")

sql += "'" + (asposecell.ismerged(dataindex - 1, column) ? asposecell.getmergedcellvalue(dataindex - 1, column) : asposecell.getcellvalue(dataindex - 1, column)).replace("'","''") + "',";

column++;

/// 得到代码表的对应值

/// <param name="property"></param>

private string getcodetablevalue(asposecell asposecell,property property,int headerindex,int dataindex)

string value=asposecell.ismerged(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, property.headertext))?asposecell.getmergedcellvalue(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, property.headertext)):asposecell.getcellvalue(dataindex-1, getcolumnindexbyheadertext(asposecell, headerindex, property.headertext)).replace("'","''");

stringbuilder sb = new stringbuilder("select distinct ");

sb.append(property.codetable.primarykey);

sb.append(" from ");

sb.append(property.codetable.name);

sb.append(" where ");

sb.append(property.codetable.referencecolumn);

sb.append("='");

sb.append(value);

sb.append("'");

if (property.datatype != "" && property.datatype != "string")

if (!validatedatatype(value, property.datatype))

throw new exception("列\"" + property.headertext + "\"中存在非\"" + property.datatype + "\"类型数据!");

if (property.datalength != 0 && property.datalength != 5000)

if (!validatedatalength(value, property.datalength))

throw new exception("列\"" + property.headertext + "\"中存长度超过\"" + property.datalength.tostring() + "\"的数据!");

if (dbhelper.executescalar(commandtype.text, sb.tostring()) != null)

return dbhelper.executescalar(commandtype.text, sb.tostring()).tostring();

throw new exception("没有对应的代码表值!");

//初始化,主要将excel文件和配置类对应关系存放到configs对象中,方便以后遍历

private void initconfig()

configs=new dictionary<string,config>();

list<string> excelfullnames=new list<string>();

if(myfillebase.directorybeing(excelpath))//判断目录是否存在(注意:除了多套excel对应多套模板,还可能有一个模板对应多个excel的情况)

filesearch.initfileinfolist();

list<string> excelconfigfilefullnames= filesearch.getfileinfo(".xml", confighelper.instance().excelpath, true, true);//在目录中查找所有名称中包含".xml"的文件

if (excelconfigfilefullnames.count == 1)//说明是一个excel对应一个xml配置文件的情况

addconfigsbyxmlfullnamehasnothingtoexcelname(excelconfigfilefullnames[0]);

else if(excelconfigfilefullnames.count>1)//说明目录中有多个xml文件,对应多个excel

foreach (string excelconfigfilefullname in excelconfigfilefullnames)

addconfigsbyxmlfullname(excelconfigfilefullname);

throw new exception("所指定目录不包含任何xlm模板,请重新指定!");

else//说明指定的不是目录而是excel文件路径

addconfigbyexcelfullname(excelpath);

//根据excel全路径构造路径和配置类对应关系(主要用于指导excel全路径的情况)

private void addconfigbyexcelfullname(string excelfullname)

string excelconfigfilefullname = myfillebase.getdirectorybyfullname(excelfullname) + "\\" + myfillebase.getfilenamewithoutextension(excelfullname) + ".xml";

config config=null;

if (myfillebase.filebeing(excelconfigfilefullname))

config = new config(excelconfigfilefullname);//创建配置(config)对象

configs.add(excelfullname, config);

throw new exception("所指定文件没有对应的配置文件,请重新指定!");

//根据xml文件全路径构造路径和配置类对应关系(得到一个xml文件对应的所有excel然后构造config对象存放到configs中)

private void addconfigsbyxmlfullname(string xmlfullname)

string exceldirectory = myfillebase.getdirectorybyfullname(xmlfullname);//根据路径取得对应的目录

list<string> excelfullnames = filesearch.getfileinfo(myfillebase.getfilenamewithoutextension(xmlfullname), exceldirectory, true, true);//根据xml的名称搜索包含此名称的文件

if (excelfullnames.count >= 1)

foreach (string excelfullname in excelfullnames)

if (excelfullnames.indexof(".xls") != -1)//必须是excel文件(排除xml文件)

config = new config(xmlfullname);

throw new exception("所指定模板不包含对应的excel文件,请重新指定!");

//根据xml文件全路径构造路径和配置类对应关系(此种情况由于只有一个xml,必然对应一个或多个excel文件,所以只需要查找excel文件即可)

private void addconfigsbyxmlfullnamehasnothingtoexcelname(string xmlfullname)

config config = null;

string exceldirectory=myfillebase.getdirectorybyfullname(xmlfullname);

list<string> excelfullnames = filesearch.getfileinfo(".xls", exceldirectory, true, true);

通用Excel导入设计

sqlhelper:数据库操作类,使用时在配置文件的connectionstrings中配置name为"dbcon"的连接串,指明providername即可,如果不使用配置可以直接在构造函数中传递这两个参数。

myxml:对于xml文件操作的封装了,用于xml文件操作。

myfilebase:对文件操作的封装。

filesearch:对文件查找的封装,可以按照关键字查找文件。

为了更加容易理解,我对程序中的一些约定和处理做少许补充。

excel类中有参构造函数两个参数分别是excel路径(也可以是目录)以及是否启用事务的bool型变量。如果用户使用无参构造函数的话,就必须在应用程序配置文件的appsettings配置节点配置中配置"excelpath"和"usetransaction"两个节点。由于对数据库的操作需要访问应用程序的配置文件,因此需要配置connectionstrings节点。

一般的导入按照上面的配置就可以完成了。为了方便使用此类还提供了其他导入方式。假如觉得列配置较麻烦的,觉得没有必要配置那么多列的话,可以考虑下面几种方式。

ⅰ 配置文件中如果没有column配置,可以通过配置单元格的别名,来指示每一个列对应的表字段。

ⅱ 如果配置文件中没有column配置,而又不希望指定单元格别名,但是excel中的列和表中的列又不是一一对应的(很可能有些列数据库表中有,而excel中没有),此时如果excel中列的顺序和表中顺序一致,你就可以通过在配置文件中设置table的excludedcolumns来将这些列排除(多个需要排除的列中间用","分割)。

ⅲ 如果我的excel中的列和数据库表中完全一致且顺序一样,那么你出来配置文件中配置table属性外就不需要任何额外的配置了。

另外,如果需要在导入时检查是否有默写列唯一的情况的情况(例如productname我不希望有重复),对于重复的先删除再倒入,此时可以再此列上设置isprimarykey为true,然后在table的属性中配置deleterepeat为true就可以了;如果所有的导入过程中你需要使用事务机制,可以在应用程序配置appsettings 配置节点中指定usetransaction为true(注意先要保证事务服务是启动的);程序支持合并行的导入。

关于配置文件和excel文件的关系,是这样约定的,多数情况下excelpath的配置为目录(当然可以是一个excel文件路径,此时就只导入该excel文件),对于此种情形可能出现下列情况。

ⅰ 目录中只有一个配置文件,而有一个或多个excel。这种情况下程序认为此配置文件对应所有excel文件,将会使用此配置将所有excel导入。

ⅱ 目录中有多个配置文件,并且有多个excel文件。此时程序户根据配置文件的名称自动匹配excel文件,匹配的规则就是它对应的excle文件的名称中要出现配置文件的名称。

下面我们简单的测试一下我们的类库,应该说使用起来十分简单。

ⅰ 在使用之前当然要有一个需要导入的excel

通用Excel导入设计

ⅱ 根据excel编写xml文件

通用Excel导入设计
通用Excel导入设计

<config endtag="rowblank" headerindex="1" dataindex="2">

<table name="products" >

<column columnname="supplierid" headertext="供货商" defaultvalue="">

<codetalbe name="suppliers" primarykey="supplierid" referencecolumn="companyname"></codetalbe>

<column columnname="productname" headertext="商品名称" defaultvalue="" />

<column columnname="categoryid" headertext="商品种类" defaultvalue="">

<codetalbe name="categories" primarykey="categoryid" referencecolumn="categoryname" ></codetalbe>

<column columnname="quantityperunit" headertext="规格" defaultvalue="" />

<column columnname="unitprice" headertext="单价" defaultvalue="" />

<column columnname="unitsinstock" headertext="库存" defaultvalue="" />

<column columnname="discontinued" headertext="是否停产" defaultvalue="" />

通用Excel导入设计

ⅲ 将excel文件和对应xml文件放到f:\cmj.dataexchange\wftest\excel

ⅳ 建立一个项目,添加cmj.dataexchange.dll引用

ⅴ 在配置文件中配置数据库连接以及excel目录等

通用Excel导入设计
通用Excel导入设计

<configuration>

<appsettings>

<add key="excelpath" value="f:\cmj.dataexchange\wftest\excel"/> <!--excel文件所在路径或者其根目录(此时会将其下所有excel全部倒入)-->

<add key="usetransaction" value="true"/>

</appsettings>

<connectionstrings>

<add name="dbconstr" connectionstring="data source=.;database=northwind;integrated security=sspi" providername="system.data.sqlclient"/>

</connectionstrings>

</configuration>

通用Excel导入设计

ⅵ 接着确保distributed transaction coordinator服务是启动的(因为程序中用的是.net2.0的事务,当然你也可以使用.net1.0事务,此时就无需启动此服务了)。

ⅶ 最后添加下面两句代码就可以完成整个导入了。

excel ex = new excel();

ex.import();

下面是导入前后数据库northwind中products表中的数据(已经成功导入)

导入之前

通用Excel导入设计

导入之后

通用Excel导入设计
通用Excel导入设计