iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >利用Java怎么将excel表格批量导入到数据库
  • 345
分享到

利用Java怎么将excel表格批量导入到数据库

javaexcel数据库 2023-05-30 23:05:38 345人浏览 独家记忆
摘要

本篇文章给大家分享的是有关利用Java怎么将excel表格批量导入到数据库,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。创建导入抽象类package com.GClo

本篇文章给大家分享的是有关利用Java怎么将excel表格批量导入到数据库,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

创建导入抽象类

package com.GCloud.common.excel;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.PrintStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;import org.apache.poi.hssf.eventusermodel.FORMatTrackingHSSFListener;import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;import org.apache.poi.hssf.eventusermodel.HSSFListener;import org.apache.poi.hssf.eventusermodel.HSSFRequest;import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;import org.apache.poi.hssf.model.HSSFFormulaParser;import org.apache.poi.hssf.record.BOFRecord;import org.apache.poi.hssf.record.BlankRecord;import org.apache.poi.hssf.record.BoolErrRecord;import org.apache.poi.hssf.record.BoundSheetRecord;import org.apache.poi.hssf.record.FormulaRecord;import org.apache.poi.hssf.record.LabelRecord;import org.apache.poi.hssf.record.LabelSSTRecord;import org.apache.poi.hssf.record.NoteRecord;import org.apache.poi.hssf.record.NumberRecord;import org.apache.poi.hssf.record.RKRecord;import org.apache.poi.hssf.record.Record;import org.apache.poi.hssf.record.SSTRecord;import org.apache.poi.hssf.record.StringRecord;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public abstract class HxlsAbstract implements HSSFListener {  private int minColumns;  private POIFSFileSystem fs;  private PrintStream output;  private int lastRowNumber;  private int lastColumnNumber;    private boolean outputFormulaValues = true;    private SheetRecordCollectingListener workbookBuildingListener;  private HSSFWorkbook stubWorkbook;  // Records we pick up as we process  private SSTRecord sstRecord;  private FormatTrackingHSSFListener formatListener;    private int sheetIndex = -1;  private BoundSheetRecord[] orderedBSRs;  @SuppressWarnings("unchecked")  private ArrayList boundSheetRecords = new ArrayList();  // For handling formulas with string results  private int nextRow;  private int nextColumn;  private boolean outputNextStringRecord;  private int curRow;  private List<String> rowlist;  @SuppressWarnings( "unused")  private String sheetName;  public HxlsAbstract(POIFSFileSystem fs)      throws SQLException {    this.fs = fs;    this.output = System.out;    this.minColumns = -1;    this.curRow = 0;    this.rowlist = new ArrayList<String>();  }  public HxlsAbstract(String filename) throws IOException,      FileNotFoundException, SQLException {    this(new POIFSFileSystem(new FileInputStream(filename)));  }  //excel记录行操作方法,以行索引和行元素列表为参数,对一行元素进行操作,元素为String类型// public abstract void optRows(int curRow, List<String> rowlist) throws SQLException ;  //excel记录行操作方法,以sheet索引,行索引和行元素列表为参数,对sheet的一行元素进行操作,元素为String类型  public abstract void optRows(int sheetIndex,int curRow, List<String> rowlist) throws Exception;    public void process() throws IOException {    MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(        this);    formatListener = new FormatTrackingHSSFListener(listener);    HSSFEventFactory factory = new HSSFEventFactory();    HSSFRequest request = new HSSFRequest();    if (outputFormulaValues) {      request.addListenerForAllRecords(formatListener);    } else {      workbookBuildingListener = new SheetRecordCollectingListener(          formatListener);      request.addListenerForAllRecords(workbookBuildingListener);    }    factory.processWorkbookEvents(request, fs);  }    @SuppressWarnings("unchecked")  public void processRecord(Record record) {    int thisRow = -1;    int thisColumn = -1;    String thisStr = null;    String value = null;    switch (record.getSid()) {    case BoundSheetRecord.sid:      boundSheetRecords.add(record);      break;    case BOFRecord.sid:      BOFRecord br = (BOFRecord) record;      //进入sheet      if (br.getType() == BOFRecord.TYPE_WORKSHEET) {        // Create sub workbook if required        if (workbookBuildingListener != null && stubWorkbook == null) {          stubWorkbook = workbookBuildingListener              .getStubHSSFWorkbook();        }        // Works by ordering the BSRs by the location of        // their BOFRecords, and then knowing that we        // process BOFRecords in byte offset order        sheetIndex++;        if (orderedBSRs == null) {          orderedBSRs = BoundSheetRecord              .orderByBofPosition(boundSheetRecords);        }        sheetName = orderedBSRs[sheetIndex].getSheetname();      }      break;    case SSTRecord.sid:      sstRecord = (SSTRecord) record;      break;    case BlankRecord.sid:      BlankRecord brec = (BlankRecord) record;      thisRow = brec.getRow();      thisColumn = brec.getColumn();      thisStr = "";      break;    case BoolErrRecord.sid:      BoolErrRecord berec = (BoolErrRecord) record;      thisRow = berec.getRow();      thisColumn = berec.getColumn();      thisStr = "";      break;    case FormulaRecord.sid:      FormulaRecord frec = (FormulaRecord) record;      thisRow = frec.getRow();      thisColumn = frec.getColumn();      if (outputFormulaValues) {        if (Double.isNaN(frec.getValue())) {          // Formula result is a string          // This is stored in the next record          outputNextStringRecord = true;          nextRow = frec.getRow();          nextColumn = frec.getColumn();        } else {          thisStr = formatListener.formatNumberDateCell(frec);        }      } else {        thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook,            frec.getParsedExpression()) + '"';      }      break;    case StringRecord.sid:      if (outputNextStringRecord) {        // String for formula        StringRecord srec = (StringRecord) record;        thisStr = srec.getString();        thisRow = nextRow;        thisColumn = nextColumn;        outputNextStringRecord = false;      }      break;    case LabelRecord.sid:      LabelRecord lrec = (LabelRecord) record;      curRow = thisRow = lrec.getRow();      thisColumn = lrec.getColumn();      value = lrec.getValue().trim();      value = value.equals("")?" ":value;      this.rowlist.add(thisColumn, value);      break;    case LabelSSTRecord.sid:      LabelSSTRecord lsrec = (LabelSSTRecord) record;      curRow = thisRow = lsrec.getRow();      thisColumn = lsrec.getColumn();      if (sstRecord == null) {        rowlist.add(thisColumn, " ");      } else {        value = sstRecord        .getString(lsrec.getSSTIndex()).toString().trim();        value = value.equals("")?" ":value;        rowlist.add(thisColumn,value);      }      break;    case NoteRecord.sid:      NoteRecord nrec = (NoteRecord) record;      thisRow = nrec.getRow();      thisColumn = nrec.getColumn();      // TODO: Find object to match nrec.getShapeId()      thisStr = '"' + "(TODO)" + '"';      break;    case NumberRecord.sid:      NumberRecord numrec = (NumberRecord) record;      curRow = thisRow = numrec.getRow();      thisColumn = numrec.getColumn();      value = formatListener.formatNumberDateCell(numrec).trim();      value = value.equals("")?" ":value;      // Format      rowlist.add(thisColumn, value);      break;    case RKRecord.sid:      RKRecord rkrec = (RKRecord) record;      thisRow = rkrec.getRow();      thisColumn = rkrec.getColumn();      thisStr = '"' + "(TODO)" + '"';      break;    default:      break;    }    // 遇到新行的操作    if (thisRow != -1 && thisRow != lastRowNumber) {      lastColumnNumber = -1;    }    // 空值的操作    if (record instanceof MissingCellDummyRecord) {      MissingCellDummyRecord mc = (MissingCellDummyRecord) record;      curRow = thisRow = mc.getRow();      thisColumn = mc.getColumn();      rowlist.add(thisColumn," ");    }    // 如果遇到能打印的东西,在这里打印    if (thisStr != null) {      if (thisColumn > 0) {        output.print(',');      }      output.print(thisStr);    }    // 更新行和列的值    if (thisRow > -1)      lastRowNumber = thisRow;    if (thisColumn > -1)      lastColumnNumber = thisColumn;    // 行结束时的操作    if (record instanceof LastCellOfRowDummyRecord) {      if (minColumns > 0) {        // 列值重新置空        if (lastColumnNumber == -1) {          lastColumnNumber = 0;        }      }      // 行结束时, 调用 optRows() 方法      lastColumnNumber = -1;      try {        optRows(sheetIndex,curRow, rowlist);      } catch (Exception e) {        e.printStackTrace();      }      rowlist.clear();    }  }}

创建导入接口

package com.gcloud.common.excel;import java.util.List;public interface HxlsOptRowsInterface {  public static final String SUCCESS="success";    public String optRows(int sheetIndex, int curRow, List<String> rowlist) throws Exception;}

创建实现类, 在这个方法实现把导入的数据添加到数据库

package com.gcloud.common.excel;import java.util.List;public class HxlsInterfaceImpl implements HxlsOptRowsInterface {  @Override  public String optRows(int sheetIndex, int curRow, List<String> datalist)      throws Exception {    //在这里执行数据的插入    //System.out.println(rowlist);    //saveData(datalist);    return "";  }}

导入工具实现

package com.gcloud.common.excel;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class ExcelImportUtil extends HxlsAbstract{  //数据处理bean  private HxlsOptRowsInterface hxlsOptRowsInterface;  //处理数据总数  private int optRows_sum = 0;  //处理数据成功数量  private int optRows_success = 0;  //处理数据失败数量  private int optRows_failure = 0;  //excel表格每列标题  private List<String> rowtitle ;  //失败数据  private List<List<String>> failrows;  //失败原因  private List<String> failmsgs ;  //要处理数据所在的sheet索引,从0开始  private int sheetIndex;  public ExcelImportUtil(String filename, int sheetIndex, HxlsOptRowsInterface hxlsOptRowsInterface) throws IOException,      FileNotFoundException, SQLException {    super(filename);    this.sheetIndex = sheetIndex;    this.hxlsOptRowsInterface = hxlsOptRowsInterface;    this.rowtitle = new ArrayList<String>();    this.failrows = new ArrayList<List<String>>();    this.failmsgs = new ArrayList<String>();  }  @Override  public void optRows(int sheetIndex,int curRow, List<String> rowlist) throws Exception {        //将rowlist的长度补齐和标题一致    int k=rowtitle.size()-rowlist.size();    for(int i=0;i<k;i++){      rowlist.add(null);    }    if(sheetIndex == this.sheetIndex){      optRows_sum++;      if(curRow == 0){//记录标题        rowtitle.addAll(rowlist);      }else{        String result = hxlsOptRowsInterface.optRows(sheetIndex, curRow, rowlist);        if(!result.equals(hxlsOptRowsInterface.SUCCESS)){          optRows_failure++;          //失败数据          failrows.add(new ArrayList<String>(rowlist));          failmsgs.add(result);        }else{          optRows_success++;        }      }    }  }  public long getOptRows_sum() {    return optRows_sum;  }  public void setOptRows_sum(int optRows_sum) {    this.optRows_sum = optRows_sum;  }  public long getOptRows_success() {    return optRows_success;  }  public void setOptRows_success(int optRows_success) {    this.optRows_success = optRows_success;  }  public long getOptRows_failure() {    return optRows_failure;  }  public void setOptRows_failure(int optRows_failure) {    this.optRows_failure = optRows_failure;  }  public List<String> getRowtitle() {    return rowtitle;  }  public List<List<String>> getFailrows() {    return failrows;  }  public List<String> getFailmsgs() {    return failmsgs;  }  public void setFailmsgs(List<String> failmsgs) {    this.failmsgs = failmsgs;  }}

导入实现方法:

public static void main(String[] args){    ExcelImportUtil importUtil;    try {      importUtil = new ExcelImportUtil("d:/data.xls",0, new HxlsInterfaceImpl());      importUtil.process();    } catch (FileNotFoundException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    } catch (SQLException e) {      e.printStackTrace();    }}

以上就是利用Java怎么将excel表格批量导入到数据库,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网精选频道。

--结束END--

本文标题: 利用Java怎么将excel表格批量导入到数据库

本文链接: https://www.lsjlt.com/news/222074.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • c++中函数返回值的类型是由什么决定的
    在 c++ 中,函数返回值类型由其函数原型的类型决定,包括:函数原型指定返回值类型:在函数名称后跟冒号,再跟返回值类型。默认返回值类型为 int:如果不指定返回值类型,默认类型为 int...
    99+
    2024-05-14
    c++
  • 在c++中,什么叫函数的返回值
    在 c++ 中,函数只能返回一个值。解决方法:引用传递、结构体或类、out 参数。没有返回值的函数可以使用 void 类型,表示不返回任何值。 什么是 C++ 中函数的返回值? 在 C...
    99+
    2024-05-14
    c++
  • c++中static的作用和用法
    c++ 中的 static 关键字用于声明静态变量、函数或类成员,使其在程序生命周期内存在或与类的每个实例关联。具体用法如下:静态变量:在函数外声明,仅创建一份副本,在程序启动时初始化且...
    99+
    2024-05-14
    c++
  • static在c和c++中的区别
    static关键字在c和c++中用于控制变量的生命周期和作用域。在c中,它延长局部变量和限制全局变量的作用域。在c++中,它还用于定义类成员变量和函数、命名空间中的变量和函数,以及函数内...
    99+
    2024-05-14
    c语言 c++ 作用域
  • c++中a++与++a的区别
    c++ 中 a++ 和 ++a 区别:后缀递增 a++ 先返回原始值,再递增;前缀递增 ++a 先递增,再返回递增后的值。 C++ 中 a++ 与 ++a 的区别 在 C++ 中,a+...
    99+
    2024-05-14
    c++
  • if else在c++中的用法
    在 c++ 中,if else 语句根据条件执行不同代码块的语法为:if (condition) { } else { }。它可用于:检查数字是否为正数根据条件执行嵌套 if els...
    99+
    2024-05-14
    c++
  • struct在c和c++中的区别
    c和c++中struct的区别包括:c中成员默认公开访问,c++中默认私有访问。c++可以在struct定义中初始化成员,c中不允许。c++支持成员函数,c不支持。c++不支持匿名str...
    99+
    2024-05-14
    c++
  • c++中的所有函数都是传值调用吗
    函数调用类型可分为传值调用和引用调用,默认采用传值调用,传值调用中形参接收实参副本,引用调用中形参接收实参引用,对形参进行的修改也会影响实参。 C++中的函数调用类型 C++中,函数调...
    99+
    2024-05-14
    c++
  • c++中ifdef的用法
    c++ 中的 #ifdef 预处理器指令用于根据预定义宏是否存在来编译或不编译代码块。它的语法是 #ifdef ,其作用包括:检查宏是否存在,如果宏已定义,则编译其后的代码块;实现条件编...
    99+
    2024-05-14
    c++
  • c++中的函数调用有哪几种方式?它们有什么区别
    c++ 中的函数调用方式有 4 种:值传递(复制实参值,不影响实参)、引用传递(传递实参地址,修改形参值会修改实参)、指针传递(传递实参指向的内存地址,修改指向的值会影响实参)、rval...
    99+
    2024-05-14
    c++
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作