EXCEL数据导入数据库

来源:互联网 发布:unix高级编程 编辑:程序博客网 时间:2024/05/03 20:19
1、类设计,EXCEL要据配置读入DATASET

using System;
using System.Data;
using System.Collections;
using System.Data.OleDb;

namespace HKH.Common

 /// <summary>
 /// Excel 表格中 列标头 与 列索引 的对应转换
 /// </summary>
 /// <remarks>Create By Liwt on 2006 - 09 - 15
 /// </remarks>
 enum EnumExcelColumn
 {
  A = 0,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,
  AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO,AP,AQ,AR,AS,AT,AU,AV,AW,AX,AY,AZ,
  BA,BB,BC,BD,BE,BF,BG,BH,BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,
  CA,CB,CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CM,CN,CO,CP,CQ,CR,CS,CT,CU,CV,CW,CX,CY,CZ,
  DA,DB,DC,DD,DE,DF,DG,DH,DI,DJ,DK,DL,DM,DN,DO,DP,DQ,DR,DS,DT,DU,DV,DW,DX,DY,DZ,
  EA,EB,EC,ED,EE,EF,EG,EH,EI,EJ,EK,EL,EM,EN,EO,EP,EQ,ER,ES,ET,EU,EV,EW,EX,EY,EZ,
  FA,FB,FC,FD,FE,FF,FG,FH,FI,FJ,FK,FL,FM,FN,FO,FP,FQ,FR,FS,FT,FU,FV,FW,FX,FY,FZ,
  GA,GB,GC,GD,GE,GF,GG,GH,GI,GJ,GK,GL,GM,GN,GO,GP,GQ,GR,GS,GT,GU,GV,GW,GX,GY,GZ,
  HA,HB,HC,HD,HE,HF,HG,HH,HI,HJ,HK,HL,HM,HN,HO,HP,HQ,HR,HS,HT,HU,HV,HW,HX,HY,HZ,
  IA,IB,IC,ID,IE,IF,IG,IH,II,IJ,IK,IL,IM,IN,IO,IP,IQ,IR,IS,IT,IU,IV
 }

 /// <summary>
 /// 从Excel导入数据到DataSet,带有虚函数的基类
 /// </summary>
 /// <remarks>Create By Liwt on 2006 - 09 - 15
 /// </remarks>
 public class clsImportExcel
 {
  #region 变量

  protected String m_MappingFile;     //映射配置文件路径
  protected String m_ExcelSheetName;    //Excel中要导入数据的表名
  protected String m_SqlTableName;    //要导入的Sql表名,也可为其它类型的,如Oracle
  protected ArrayList[] m_ColumnMapping;   //列映射配置列表,包括3部分 0--Sql列名,1--Excel列索引
              //2-- 如当前Excel行为空,是否赋值为上一行的值
  private bool isLoadMapping;

  #endregion

  #region 构造函数

  /// <summary>
  /// 无参构造
  /// </summary>
  public clsImportExcel()
  {
   m_MappingFile = "";
   m_ExcelSheetName = "";
   isLoadMapping = false;
   m_ColumnMapping = new ArrayList[3];
   
   m_ColumnMapping[0] = new ArrayList();
   m_ColumnMapping[1] = new ArrayList();
   m_ColumnMapping[2] = new ArrayList();
  }

  /// <summary>
  /// 构造函数重载
  /// </summary>
  /// <param name="mappingFilePath">映射配置文件路径</param>
  /// <param name="excelSheetName">Excel中要导入数据的表名</param>
  public clsImportExcel(String mappingFilePath, String excelSheetName)
  {
   m_MappingFile = mappingFilePath;
   m_ExcelSheetName = excelSheetName;
   isLoadMapping = false;
   m_ColumnMapping = new ArrayList[3];

   m_ColumnMapping[0] = new ArrayList();
   m_ColumnMapping[1] = new ArrayList();
   m_ColumnMapping[2] = new ArrayList();
  }

  #endregion

  #region 属性

  /// <summary>
  /// 读取或设置 映射配置文件路径
  /// </summary>
  public String MappingFilePath
  {
   get
   {
    return m_MappingFile;
   }
   set
   {
    m_MappingFile = value;
    isLoadMapping = false;
   }
  }

  /// <summary>
  /// 读取或设置 Excel中要导入数据的表名
  /// </summary>
  public String ExcelSheetName
  {
   get
   {
    return m_ExcelSheetName;
   }
   set
   {
    m_ExcelSheetName = value;
    isLoadMapping = false;
   }
  }

  #endregion

  #region 公共方法

  /// <summary>
  /// 导入数据
  /// </summary>
  /// <param name="excelFilePath">要导入的Excel文件路径</param>
  /// <param name="dsTarget">目标DataSet</param>
  /// <returns>ture -- 成功, false -- 失败
  /// </returns>
  public bool Import(String excelFilePath,ref DataSet dsTarget)
  {
   try
   {
    if (!isLoadMapping)
    {
     if (!LoadMapping())
     {
      return false;
     }
    }

    //利用Ole读取Excel数据
    OleDbConnection oleConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + excelFilePath + ";");
    OleDbDataAdapter oleDA = new OleDbDataAdapter("SELECT * FROM [" + m_ExcelSheetName + "$]",oleConn);

    DataSet dsExcel = new DataSet();
    oleDA.Fill(dsExcel,m_ExcelSheetName);

    oleDA.Dispose();
    oleConn.Dispose();

    //对建立数据行缓存,以备填充对空单元格进行处理
    DataRow tempRow = dsExcel.Tables[m_ExcelSheetName].Rows[0];

    for ( int i = 0 ;i<dsExcel.Tables[m_ExcelSheetName].Rows.Count; i ++ )
    {
     DataRow excelRow = dsExcel.Tables[m_ExcelSheetName].Rows[i];

     //调用导入前数据处理函数,并根据返回值确定下一步处理
     if (!ImportingBefore(ref excelRow))
     {
      continue;
     }

     DataRow sqlNewRow = dsTarget.Tables[0].NewRow();

     for ( int j = 0 ;j<m_ColumnMapping[0].Count; j ++ )
     {
      String sqlColName = m_ColumnMapping[0][j].ToString();
      int excelColindex = (int)m_ColumnMapping[1][j];
      bool inherit = Convert.ToBoolean(m_ColumnMapping[2][j]);

      //如果当前行当前列为空
      if (Convert.IsDBNull(excelRow[excelColindex]))
      {
       //如果允许以临时值填充
       if (inherit)
       {
        sqlNewRow[sqlColName] = tempRow[excelColindex];
       }
      }
      else
      {
       //填充数据,更新缓存行数据
       sqlNewRow[sqlColName] = excelRow[excelColindex];
       tempRow[excelColindex] = excelRow[excelColindex];
      }

     }

     //调用导入后数据处理,并根据返回值决定下一步处理
     if (ImportingAfter(ref sqlNewRow))
     {
      dsTarget.Tables[0].Rows.Add(sqlNewRow);
     }
    }

    return true;
   }
   catch
   {
    return false;
   }
  }

  #endregion

  #region 受保护的虚函数,子类须重写

  /// <summary>
  /// 在导入前对Excel行数据进行处理
  /// </summary>
  /// <param name="drExcelRow">正在读取的当前Excel行</param>
  /// <returns>true -- 继续处理,false -- 跳过当前行
  /// </returns>
  protected virtual bool ImportingBefore(ref DataRow drExcelRow)
  {
   return true;
  }

  /// <summary>
  /// 在数据转存后对当前行进行处理
  /// </summary>
  /// <param name="drSqlRow">已经转存数据的当前Sql行</param>
  /// <returns>true -- 继续处理,false -- 跳过当前行
  /// </returns>
  protected virtual bool ImportingAfter(ref DataRow drSqlRow)
  {
   return true;
  }

  #endregion

  #region 私有方法

  /// <summary>
  /// 加载配置文件,取得表和列的映射
  /// </summary>
  /// <returns></returns>
  private bool LoadMapping()
  {
   try
   {
    //清除已过时的配置
    m_ColumnMapping[0].Clear();
    m_ColumnMapping[1].Clear();
    m_ColumnMapping[2].Clear();

    if (m_MappingFile == null || m_MappingFile == "")
    {
     throw new Exception("找不到配置文件");
    }

    //读入配置文件
    DataSet dsMaping = new DataSet();
    dsMaping.ReadXml(m_MappingFile);

    if (dsMaping.Tables.Count == 0)
    {
     throw new Exception("读取配置文件失败");
    }

    //读取表映射
    DataRow[] tableMap = dsMaping.Tables["TableMapping"].Select("excelSheet='" + m_ExcelSheetName + "'");

    if (tableMap.Length != 1)
    {
     throw new Exception("该Sheet不存在或多次配置");
    }

    //读取列映射
    DataRow[] colMap = dsMaping.Tables["ColumnMapping"].Select("TableMapping_id="+tableMap[0]["TableMapping_id"].ToString());

    if (colMap.Length <= 0)
    {
     throw new Exception("没有为该表配置列映射");
    }

    for (int i = 0; i < colMap.Length; i ++)
    {
     m_ColumnMapping[0].Add(colMap[i]["sqlCol"]);
     m_ColumnMapping[1].Add((int)Enum.Parse(typeof(EnumExcelColumn),colMap[i]["excelCol"].ToString(),true));
     m_ColumnMapping[2].Add(colMap[i]["inherit"]);
    }

    //设置为已加载配置
    isLoadMapping = true;

    return true;
   }
   catch
   {
    return false;
   }
  }

  #endregion
 }
}

2、配置文件XSD

3、 配置文件样例

excelSheet ----要导入数据库的EXCEL文件中的工作薄名

SQLTABLE---要导入的数据库表名

EXCELCOL--EXCEL表中列标头

SQLCOL--SQL数据库中列名

inherit---当EXCEL中有表格合并时,是否继续上面的单元格值,此处用于拆解单元格,本处指合并行,TRUE为拆解,即所有单元格都以合并值填充,为FALSE则第一行为填充值,其它各行以空填充

<ImportConfiguration>
 <TableMapping excelSheet="Sheet1" sqlTable="CNKI_illegalIPInfo">
  <ColumnMapping excelCol="A" sqlCol="UnitName" inherit="false"/>
  <ColumnMapping excelCol="B" sqlCol="StartIP" inherit="false"/>
  <ColumnMapping excelCol="C" sqlCol="EndIP" inherit="false"/>
 </TableMapping>
</ImportConfiguration>