关于excel在asp.net中使用

本文介绍了.Net使用Excel表的两种方式,一种通过oldb连接,另一种引用Excel对象编程。还分享了导入Excel数据到数据库的项目经验,借用Provider模式,定义Excel对应数据表关系对象,编写转换器完成数据导入,此方式也可用于导出Excel。

.Net使用excel表有两种方式,
一种是通过oldb来进行连接,把excel表作为数据库来处理。
另一种则是通过引用excel对象,进行对象编程来,调用excel的函数方法。

总的来说,第一种很方便,但缺乏变化,第二种很灵活,但是,缺乏规律性。
具体使用中,看来还是要看情况来操作。

第一种情况,是不需要asp.net作什么额外动作,
第二种情况,需要使用tblim.exe来将excel的com转换成为托管主件,才能在import namespace。
其实,也可以有vs.net进行转换,更为方便。
一旦引用excel namespace,其后的编程就能根据excel帮助里面的编程指南,调用它的对象,方法,属性等等。

我在想,今后把它写成一个webservice可以随意从数据库中,将数据倒出来。

the following content updated on 2005-11-23
===================================
其实,我们经常适用到的还是第二种模式。
最近我接到一个项目用到的导入Excel数据的问题,我把我的经验和代码共享出来。

这个项目的Excel的导入假定条件是:
1.有几个range是固定值
2.有一个整块的数据内容区(range)
3.可能有多个符合上面1、2要求,但具体格式不一致的Excel模板。
4.几个不同模板可能导入不同数据库

当时由于正在看DOTTEXT代码,对其中Provider这种模式非常感兴趣,考虑了一番认为这个Excel导入项目可以借用Provider模式。

对Provider模式的解释


无论源对象是什么,通过IProvider接口,我们可以得到一个较为统一的对象,也就是说同IProvider,我们屏蔽对源数据对象的处理细节,而完成得到一个符合我们要求的目的对象。

--这段解释完全是自己的理解和体会,请大家斧正



综合考虑后,我觉得我应该有一个对象来描述目前Excel格式内容,比如:描述固定range,描述不固定的数据块的开始地方(range),从第几列到第几列是数据区,同时定义输入限制数据类型。

我命名这个对象为:ExcelMapDB


ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
InBlock.gif    
/// ExcelMapDB 的摘要说明。
InBlock.gif    
/// Author:King astar
InBlock.gif    
/// Date:2005-10-27
InBlock.gif    
/// Description:用来描述Excel列对应数据列的关系
InBlock.gif    
/// </summary>
ExpandedBlockEnd.gif    
/// 

None.gif    [Serializable]
None.gif    
public class ExcelMapDB
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
private bool _isfixed = false;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 是否是固定列
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// 

InBlock.gif        [XmlAttribute("IsFixed")]
InBlock.gif        
public bool IsFixed
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
getdot.gif{return _isfixed;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
setdot.gif{_isfixed = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private String _rowshowName="";
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 对应的datarow的显示名称是什么
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// 

InBlock.gif        [XmlAttribute("RowShowName")]
InBlock.gif        
public String RowShowName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
getdot.gif{return _rowshowName;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
setdot.gif{_rowshowName = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
private String _rowName;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 对应的datarow的列名是什么
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// 

InBlock.gif        [XmlAttribute("RowName")]
InBlock.gif        
public String RowName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
getdot.gif{return _rowName;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
setdot.gif{_rowName = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private String _excelRangeName;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 如果是固定列则直接读取rangName;
InBlock.gif        
/// eg. A2 B3 etcdot.gif.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// 

InBlock.gif        [XmlAttribute("ExcelRangeName")]
InBlock.gif        
public String ExcelRangeName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
getdot.gif{return _excelRangeName;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
setdot.gif{_excelRangeName = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private int _offSetStartRange;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 如果是相对列,则使用相对开始列的Y轴的距离来得到值
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// 

InBlock.gif        [XmlAttribute("OffYSetStartRange")]
InBlock.gif        
public int OffYSetStartRange
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
getdot.gif{return _offSetStartRange;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
setdot.gif{_offSetStartRange = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
InBlock.gif        
public ExcelMapDB()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// TODO: 在此处添加构造函数逻辑
InBlock.gif            
//
ExpandedSubBlockEnd.gif
        }

ExpandedBlockEnd.gif    }

 序列化对象的XML
 1None.gif<?xml version="1.0" encoding="utf-8"?>
 2None.gif<ExcelMapDbRelation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DataTableProviderType="QAComponents.Codes.Provider.BaseDataTableProvider, QAComponents.Codes" ExcelStartRangeName="A6" ConvertorType="QAComponents.Codes.Convertor.BaseConvertor, QAComponents.Codes">
 3None.gif  <RelationItems>
 4None.gif    <ExcelMapDB IsFixed="true" RowName="Temp1" ExcelRangeName="D4" OffYSetStartRange="0" />
 5None.gif    <ExcelMapDB IsFixed="true" RowName="Temp2" ExcelRangeName="L4" OffYSetStartRange="0" />
 6None.gif    <ExcelMapDB IsFixed="true" RowName="Temp3" ExcelRangeName="T4" OffYSetStartRange="0" />
 7None.gif    <ExcelMapDB IsFixed="false" RowName="SerialNo" ExcelRangeName="" OffYSetStartRange="0" />
 8None.gif    <ExcelMapDB IsFixed="false" RowName="Ith1" ExcelRangeName="" OffYSetStartRange="1" />
 9None.gif    <ExcelMapDB IsFixed="false" RowName="Vf1" ExcelRangeName="" OffYSetStartRange="2" />
10None.gif    <ExcelMapDB IsFixed="false" RowName="Pf1" ExcelRangeName="3" OffYSetStartRange="3" />
11None.gif    <ExcelMapDB IsFixed="false" RowName="ImPf1" ExcelRangeName="4" OffYSetStartRange="4" />
12None.gif    <ExcelMapDB IsFixed="false" RowName="SE1" ExcelRangeName="5" OffYSetStartRange="5" />
13None.gif    <ExcelMapDB IsFixed="false" RowName="SMSR1" ExcelRangeName="6" OffYSetStartRange="6" />
14None.gif    <ExcelMapDB IsFixed="false" RowName="A1" ExcelRangeName="7" OffYSetStartRange="7" />
15None.gif    <ExcelMapDB IsFixed="false" RowName="B1" ExcelRangeName="8" OffYSetStartRange="8" />
16None.gif    
17None.gif    
18None.gif    <ExcelMapDB IsFixed="false" RowName="Ith12" ExcelRangeName="9" OffYSetStartRange="9" />
19None.gif    <ExcelMapDB IsFixed="false" RowName="Vf2" ExcelRangeName="10" OffYSetStartRange="10" />
20None.gif    <ExcelMapDB IsFixed="false" RowName="Pf2" ExcelRangeName="11" OffYSetStartRange="11" />
21None.gif    <ExcelMapDB IsFixed="false" RowName="ImPf2" ExcelRangeName="12" OffYSetStartRange="12" />
22None.gif    <ExcelMapDB IsFixed="false" RowName="SE2" ExcelRangeName="13" OffYSetStartRange="13" />
23None.gif    <ExcelMapDB IsFixed="false" RowName="SMSR2" ExcelRangeName="14" OffYSetStartRange="14" />
24None.gif    <ExcelMapDB IsFixed="false" RowName="A2" ExcelRangeName="15" OffYSetStartRange="15" />
25None.gif    <ExcelMapDB IsFixed="false" RowName="B2" ExcelRangeName="16" OffYSetStartRange="16" />
26None.gif    
27None.gif    <ExcelMapDB IsFixed="false" RowName="Sen" ExcelRangeName="17" OffYSetStartRange="17" />
28None.gif    <ExcelMapDB IsFixed="false" RowName="Vbr" ExcelRangeName="18" OffYSetStartRange="18" />
29None.gif    <ExcelMapDB IsFixed="false" RowName="Vop" ExcelRangeName="19" OffYSetStartRange="19" />
30None.gif    <ExcelMapDB IsFixed="false" RowName="Iop" ExcelRangeName="20" OffYSetStartRange="20" />
31None.gif    <ExcelMapDB IsFixed="false" RowName="Io" ExcelRangeName="21" OffYSetStartRange="21" />
32None.gif    <ExcelMapDB IsFixed="false" RowName="Gain" ExcelRangeName="22" OffYSetStartRange="22" />
33None.gif    <ExcelMapDB IsFixed="false" RowName="FileNo" ExcelRangeName="23" OffYSetStartRange="23" />    
34None.gif    
35None.gif
36None.gif  </RelationItems>
37None.gif</ExcelMapDbRelation>

 

接着我定义Excel对应数据表的关系对象
这个对象还要考虑,它用什么转换器来转换


  1ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
  2InBlock.gif    /// ExcelMapDB 的摘要说明。
  3InBlock.gif    /// Author:King astar
  4InBlock.gif    /// Date:2005-10-27
  5InBlock.gif    /// Description:用来描述Excel表对应数据表的关系
  6ExpandedBlockEnd.gif    /// </summary>

  7None.gif    public class ExcelMapDbRelation
  8ExpandedBlockStart.gifContractedBlock.gif    dot.gif{
  9InBlock.gif        private ExcelMapDB[] _relationItems;
 10InBlock.gif        [XmlArray("RelationItems")]
 11InBlock.gif        public ExcelMapDB[] RelationItems
 12ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 13ExpandedSubBlockStart.gifContractedSubBlock.gif            getdot.gif{return _relationItems;}
 14ExpandedSubBlockStart.gifContractedSubBlock.gif            setdot.gif{_relationItems = value;}
 15ExpandedSubBlockEnd.gif        }

 16InBlock.gif
 17InBlock.gif        private String _dataTableProviderType = "BaseDataTableProvider";
 18ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 19InBlock.gif        /// 数据提供者类型名称
 20ExpandedSubBlockEnd.gif        /// </summary>

 21InBlock.gif        [XmlAttribute("DataTableProviderType")]
 22InBlock.gif        public String DataTableProviderType
 23ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 24ExpandedSubBlockStart.gifContractedSubBlock.gif            getdot.gif{return _dataTableProviderType;}            
 25ExpandedSubBlockStart.gifContractedSubBlock.gif            setdot.gif{_dataTableProviderType = value;}
 26ExpandedSubBlockEnd.gif        }

 27InBlock.gif
 28InBlock.gif        private String _excelStartRangeName;
 29ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 30InBlock.gif        /// 开始的范围;
 31InBlock.gif        /// eg. A2 B3 etcdot.gif.
 32InBlock.gif        /// </summary>
 33ExpandedSubBlockEnd.gif        /// 

 34InBlock.gif        [XmlAttribute("ExcelStartRangeName")]
 35InBlock.gif        public String ExcelStartRangeName
 36ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 37ExpandedSubBlockStart.gifContractedSubBlock.gif            getdot.gif{return _excelStartRangeName;}
 38ExpandedSubBlockStart.gifContractedSubBlock.gif            setdot.gif{_excelStartRangeName = value;}
 39ExpandedSubBlockEnd.gif        }
 
 40InBlock.gif
 41ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 42InBlock.gif        /// 取得数据提供者对象
 43ExpandedSubBlockEnd.gif        /// </summary>

 44InBlock.gif        [XmlIgnore]
 45InBlock.gif        public IDataTableProvider TableProvider
 46ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 47InBlock.gif            get
 48ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 49InBlock.gif                IDataTableProvider dprovider =null;
 50InBlock.gif                if(DataTableProviderType!=null)
 51ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 52InBlock.gif                    dprovider = (IDataTableProvider)System.Activator.CreateInstance(Type.GetType(DataTableProviderType));
 53ExpandedSubBlockEnd.gif                }

 54InBlock.gif                return dprovider;
 55ExpandedSubBlockEnd.gif            }

 56InBlock.gif    
 57InBlock.gif
 58InBlock.gif
 59ExpandedSubBlockEnd.gif        }

 60InBlock.gif
 61InBlock.gif        private String _convertorType ;
 62ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 63InBlock.gif        /// 转换器类型名称
 64ExpandedSubBlockEnd.gif        /// </summary>

 65InBlock.gif        [XmlAttribute("ConvertorType")]
 66InBlock.gif        public String ConvertorType
 67ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 68ExpandedSubBlockStart.gifContractedSubBlock.gif            getdot.gif{return _convertorType;}
 69ExpandedSubBlockStart.gifContractedSubBlock.gif            setdot.gif{_convertorType = value;}
 70ExpandedSubBlockEnd.gif        }

 71InBlock.gif
 72ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 73InBlock.gif        /// 取得转换器对象
 74ExpandedSubBlockEnd.gif        /// </summary>

 75InBlock.gif        [XmlIgnore]
 76InBlock.gif        public IConvertor DataConvertor
 77ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 78InBlock.gif            get
 79ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 80InBlock.gif                IConvertor convertor =null;
 81InBlock.gif                if(ConvertorType!=null)
 82ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 83InBlock.gif                    convertor = (IConvertor)System.Activator.CreateInstance(Type.GetType(ConvertorType));
 84ExpandedSubBlockEnd.gif                }

 85InBlock.gif                return convertor;
 86ExpandedSubBlockEnd.gif            }

 87InBlock.gif    
 88InBlock.gif
 89InBlock.gif
 90ExpandedSubBlockEnd.gif        }

 91InBlock.gif
 92InBlock.gif        
 93InBlock.gif
 94ContractedSubBlock.gifExpandedSubBlockStart.gif        constructor#region constructor
 95InBlock.gif        public ExcelMapDbRelation()
 96ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 97InBlock.gif            //
 98InBlock.gif            // TODO: 在此处添加构造函数逻辑
 99InBlock.gif            //
100ExpandedSubBlockEnd.gif        }

101ExpandedSubBlockEnd.gif        #endregion

102ExpandedBlockEnd.gif    }

103None.gif    


作了这些基础工作后,我考虑可以来写转换器的工作了,这部分工作是核心工作,在这部分数据会从Excel导入到数据库去。
看看接口

1ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
2InBlock.gif    /// IConvertor 的摘要说明。
3ExpandedBlockEnd.gif    /// </summary>

4None.gif    public interface IConvertor
5ExpandedBlockStart.gifContractedBlock.gif    dot.gif{
6InBlock.gif
7InBlock.gif        void Execute(DataTable dt,ExcelMapDB[] excelMapdbs,String fileName,String excelStartRangeName,int IdentityID);
8ExpandedBlockEnd.gif    }

只有一个Excute的方法参数分别是Excel对应关系对象,Excel文件路径,excel开始range名称,此Excel表唯一ID

然后,我写了一个BaseConvertor, 主要工作就是打开Excel文件,按照定义的Excel列与数据表列对应关系对象来抓数据,并导入到数据库中去。
请参看代码(注意:打开Excel的方法是Excel11.0版本,office 2003)

  1None.gif
  2ExpandedBlockStart.gifContractedBlock.gif    /**//// <summary>
  3InBlock.gif    /// BaseConvertor 的摘要说明。
  4InBlock.gif    /// Author:King astar
  5InBlock.gif    /// Date:2005-10-27
  6InBlock.gif    /// Description:核心类,将Excel数据导入数据库,是基类,可以继承
  7ExpandedBlockEnd.gif    /// </summary>

  8None.gif    public class BaseConvertor : IConvertor
  9ExpandedBlockStart.gifContractedBlock.gif    dot.gif{
 10InBlock.gif
 11ContractedSubBlock.gifExpandedSubBlockStart.gif        variable#region variable 
 12InBlock.gif
 13InBlock.gif        protected Excel.ApplicationClass app = null;
 14InBlock.gif        protected Excel.Workbooks wbs = null;
 15InBlock.gif
 16InBlock.gif        protected Excel.Worksheet ws = null;
 17InBlock.gif        protected Excel.Workbook wbc =null;
 18InBlock.gif        //Excel.Worksheet wsh =null;
 19InBlock.gif        protected Excel.Range firstRange = null;
 20InBlock.gif        protected Excel.Range fixedRange =null;
 21InBlock.gif        protected System.Reflection.Missing _objOpt = System.Reflection.Missing.Value;
 22InBlock.gif
 23InBlock.gif        protected int _identity;
 24InBlock.gif
 25ExpandedSubBlockEnd.gif        #endregion

 26InBlock.gif
 27InBlock.gif
 28InBlock.gif        public BaseConvertor()
 29ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 30InBlock.gif            //
 31InBlock.gif            // TODO: 在此处添加构造函数逻辑
 32InBlock.gif            //
 33ExpandedSubBlockEnd.gif        }

 34InBlock.gif
 35ContractedSubBlock.gifExpandedSubBlockStart.gif        IConvertor 成员#region IConvertor 成员
 36InBlock.gif
 37InBlock.gif        public void Execute(System.Data.DataTable dt, QAComponents.Codes.Configs.ExcelMapDB[] excelMapdbs, String fileName,String excelStartRangeName,int IdentityID)
 38ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 39InBlock.gif            _identity = IdentityID;
 40InBlock.gif            
 41InBlock.gif            
 42InBlock.gif
 43InBlock.gif            try
 44ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 45InBlock.gif                Openexcel(fileName);            
 46InBlock.gif                System.Data.DataTable myTable = FillTable(dt,excelMapdbs,excelStartRangeName);                
 47ExpandedSubBlockEnd.gif            }

 48InBlock.gif            catch(System.Exception ex)
 49ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 50InBlock.gif                throw new Exception("导入失败:"+ex.Message);
 51ExpandedSubBlockEnd.gif            }

 52InBlock.gif            finally
 53ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{                
 54InBlock.gif                Dispose();
 55InBlock.gif
 56ExpandedSubBlockEnd.gif            }

 57ExpandedSubBlockEnd.gif        }

 58InBlock.gif
 59ExpandedSubBlockEnd.gif        #endregion

 60InBlock.gif
 61InBlock.gif        public virtual void Openexcel(String fileName)
 62ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 63InBlock.gif            string FileName = @fileName;
 64InBlock.gif            FileName = FileName.Replace("/",@"\");
 65InBlock.gif            FileName = FileName.Replace(@"\\",@"\");
 66InBlock.gif
 67InBlock.gif
 68InBlock.gif            if(!System.IO.File.Exists(FileName))
 69InBlock.gif                throw new Exception("["+FileName+"]不存在!");
 70InBlock.gif
 71InBlock.gif            try
 72ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 73InBlock.gif                app = new  Excel.ApplicationClass();
 74ExpandedSubBlockEnd.gif            }

 75InBlock.gif            catch(System.Exception ex)
 76ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 77InBlock.gif                new Exception("无法实例化Excel对象;<br/>details:<hr size=1/>"+ex.Message);
 78ExpandedSubBlockEnd.gif            }

 79InBlock.gif            app.DisplayAlerts = false;
 80InBlock.gif
 81InBlock.gif//            //app.UserControl = true;
 82InBlock.gif            wbs = app.Workbooks;
 83InBlock.gif            try
 84ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 85InBlock.gif                
 86InBlock.gif                wbc  = wbs.Open(FileName,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt,_objOpt);            
 87ExpandedSubBlockEnd.gif            }

 88InBlock.gif            catch(System.Exception ex)
 89ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 90InBlock.gif                throw new Exception("无法正确打开文件;<br/>details:<hr size=1/>"+ex.Message);
 91ExpandedSubBlockEnd.gif            }

 92InBlock.gif
 93InBlock.gif
 94ExpandedSubBlockEnd.gif        }

 95InBlock.gif        public virtual void Dispose()
 96ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 97InBlock.gif            fixedRange =null;
 98InBlock.gif            firstRange = null;
 99InBlock.gif            ws = null;
100InBlock.gif            wbc = null;
101InBlock.gif                        
102InBlock.gif            if(wbs!=null)
103ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
104InBlock.gif                wbs.Close ();
105InBlock.gif                wbs = null;
106ExpandedSubBlockEnd.gif            }

107InBlock.gif            if(app!=null)
108ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
109InBlock.gif                app.Quit();
110InBlock.gif                app =null;
111ExpandedSubBlockEnd.gif            }

112InBlock.gif            
113InBlock.gif                
114InBlock.gif            
115InBlock.gif
116ExpandedSubBlockEnd.gif        }

117InBlock.gif
118InBlock.gif        public System.Data.DataTable  FillTable(System.Data.DataTable myTable,QAComponents.Codes.Configs.ExcelMapDB[] excelMapdbs,string excelStartRangeName)
119ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
120InBlock.gif            ws= (Excel.Worksheet)wbc.Worksheets.get_Item(1);
121InBlock.gif            firstRange = ws.get_Range(excelStartRangeName.Trim().ToUpper(),this._objOpt);
122InBlock.gif            int x =0;
123InBlock.gif            x = Convert.ToInt32(excelStartRangeName.Trim().ToUpper().Substring(
124InBlock.gif1,1));
125InBlock.gif            //开始循环
126InBlock.gif            while(firstRange.Value2!=null&&firstRange.Value2.ToString()!="")
127ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
128InBlock.gif                
129InBlock.gif                System.Data.DataRow dr = myTable.NewRow();
130InBlock.gif                
131InBlock.gif                for(int i=0;i<excelMapdbs.Length;i++)
132ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
133InBlock.gif                    try
134ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
135InBlock.gif                        if(excelMapdbs[i].IsFixed)
136ExpandedSubBlockStart.gifContractedSubBlock.gif                        dot.gif{
137InBlock.gif                            fixedRange = ws.get_Range(excelMapdbs[i].ExcelRangeName.Trim().ToUpper(),this._objOpt);
138InBlock.gif                            dr[excelMapdbs[i].RowName] = ConverData(dr.Table.Columns[excelMapdbs[i].RowName].DataType,fixedRange.Value2);
139ExpandedSubBlockEnd.gif                        }

140InBlock.gif                        else
141ExpandedSubBlockStart.gifContractedSubBlock.gif                        dot.gif{
142InBlock.gif                            dr[excelMapdbs[i].RowName]    = ConverData(dr.Table.Columns[excelMapdbs[i].RowName].DataType,
143InBlock.gif                                firstRange.get_Offset(_objOpt,excelMapdbs[i].OffYSetStartRange).Value2);
144InBlock.gif
145InBlock.gif#if DEBUG
146InBlock.gif                            object Checkvalue1 = firstRange.get_Offset(_objOpt,excelMapdbs[i].OffYSetStartRange).Value2;
147InBlock.gif#endif
148ExpandedSubBlockEnd.gif                        }

149ExpandedSubBlockEnd.gif                    }

150InBlock.gif                    catch(System.Exception ex)
151ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
152InBlock.gif                        throw new Exception(         
153InBlock.gif                            String.Format("<font color=red><b>导入数据失败</b></font><br/>附件编号:<b>{0}</b><br/>错误位置:X={1};Y(相对于开始格)={2};对应RowName:{3}<br/>details:<hr size=1/>{4}",
154InBlock.gif                            this._identity,
155InBlock.gif                            x,
156InBlock.gif                            excelMapdbs[i].OffYSetStartRange,
157InBlock.gif                            excelMapdbs[i].RowName,
158InBlock.gif                            ex.Message));
159InBlock.gif
160InBlock.gif
161InBlock.gif                    
162ExpandedSubBlockEnd.gif                    }

163ExpandedSubBlockEnd.gif                }

164InBlock.gif                
165InBlock.gif
166InBlock.gif                //myTable.Rows.Add(dr);
167InBlock.gif                dr["SummaryID"= this._identity;
168InBlock.gif                ImportDataRow(dr);
169InBlock.gif
170InBlock.gif
171InBlock.gif                x++;
172InBlock.gif                firstRange  = firstRange.get_Offset(1,_objOpt);
173InBlock.gif#if DEBUG
174InBlock.gif                object Checkvalue2 = firstRange.Value2;
175InBlock.gif#endif
176InBlock.gif                
177InBlock.gif
178ExpandedSubBlockEnd.gif            }

179InBlock.gif            return myTable;
180InBlock.gif            
181InBlock.gif
182ExpandedSubBlockEnd.gif        }

183InBlock.gif
184InBlock.gif        public virtual void ImportDataRow(DataRow row)
185ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
186InBlock.gif            BaseDAL b = new BaseDAL();
187InBlock.gif            b.ConfigTable(row.Table.TableName,"ID");
188InBlock.gif            b.Add(row);
189ExpandedSubBlockEnd.gif        }

190InBlock.gif
191ContractedSubBlock.gifExpandedSubBlockStart.gif        ConverData#region ConverData
192ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
193InBlock.gif        /// 根据定义在Excel列与数据表列对应关系对象中,列的数据类型定义来判定输入类型是否正确
194InBlock.gif        /// </summary>
195InBlock.gif        /// <param name="dbType"></param>
196InBlock.gif        /// <param name="o"></param>
197ExpandedSubBlockEnd.gif        /// <returns></returns>

198InBlock.gif        public virtual object ConverData(System.Type dbType,object o)
199ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
200InBlock.gif            if(o==null)
201InBlock.gif                return System.DBNull.Value;
202InBlock.gif            if(o.ToString().Trim()==""&&dbType!=typeof(System.String))
203InBlock.gif                return System.DBNull.Value;
204InBlock.gif
205InBlock.gif            if(dbType  == typeof(System.String))
206InBlock.gif                return Convert.ToString(o);
207InBlock.gif
208InBlock.gif            if(dbType== typeof( System.Int32))
209InBlock.gif                return Convert.ToInt32(o);
210InBlock.gif            
211InBlock.gif            if(dbType==typeof(System.Decimal))
212InBlock.gif                return Convert.ToDecimal(o);
213InBlock.gif
214InBlock.gif            return System.DBNull.Value;
215ExpandedSubBlockEnd.gif        }

216ExpandedSubBlockEnd.gif        #endregion
 
217InBlock.gif
218InBlock.gif
219InBlock.gif
220ExpandedBlockEnd.gif    }


至此Excel导入核心的介绍就完毕了,
抛开代码不说,解决问题的方法还是很简单。

1. 描述Excel的数据对应关系
2. 根据对应关系,进行数据转换。

解决这种问题的根本是要有良好的抽象能力,将实际事务转换为一些可以用代码描述的对象。
emteeth.gif呵呵。。。

另外补充的是这种方式也可以用以导出Excel, 由您自由想像了。






 

转载于:https://www.cnblogs.com/king_astar/archive/2004/02/10/1149.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值