1. 程式人生 > >批量匯入excel表格資料到資料庫中

批量匯入excel表格資料到資料庫中

1、建立匯入抽象類

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; /** * 匯入抽象類 * Created by charlin on 2017/9/7. */ public abstract class HxlsAbstract implements HSSFListener { private int minColumns; private POIFSFileSystem fs; private PrintStream output; private int lastRowNumber; private int lastColumnNumber; /** Should we output the formula, or the value it has? */ private boolean outputFormulaValues = true; /** For parsing Formulas */ private SheetRecordCollectingListener workbookBuildingListener; private HSSFWorkbook stubWorkbook; // Records we pick up as we process private SSTRecord sstRecord; private FormatTrackingHSSFListener formatListener; /** So we known which sheet we're on */ 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; /** * 遍歷 excel 檔案 */ 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); } /** * HSSFListener 監聽方法,處理 Record */ @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(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300

2、建立匯入介面

package com.gcloud.common.excel;

import java.util.List;

public interface HxlsOptRowsInterface {

    public static final String SUCCESS="success";
    /**
     * 處理excel檔案每行資料方法
     * @param sheetIndex
     * @param curRow
     * @param rowlist
     * @return success:成功,否則為失敗原因
     * @throws Exception
     */
    public String optRows(int sheetIndex, int curRow, List<String> rowlist) throws Exception;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3、建立實現類, 在這個方法實現把匯入的資料新增到資料庫中

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 "";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

4、匯入工具實現

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;

/**
 * excel匯入工具
 * Created by charlin on 2017/9/7.
 */
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 {
        /*for (int i = 0 ;i< rowlist.size();i++){
            System.out.print("'"+rowlist.get(i)+"',");
        }
        System.out.println();*/
        //將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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 相關推薦

    批量匯入excel表格資料資料庫

    1、建立匯入抽象類 package com.gcloud.common.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOExcept

    JAVA工具類(5) --- 批量匯入excel表格資料資料庫

    1、建立匯入抽象類 package com.gcloud.common.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IO

    解決JavaPOI匯入Excel表格資料時 日期格式資料解析錯誤的問題

    用POI匯入excel資料時,日期格式(如2018/7/7)資料預設會被解析成double格式,解決方法如下: package com.test.util; import java.text.DateFormat; import java.text.SimpleDate

    程式設計之旅-Ext4.X匯入excel表格在grid顯示

    1:關於匯入excel就不說了 網上很多教程,關鍵是在ext grid中顯示問題,其實就是對Ext的瞭解和api熟悉程度不高。 目前在ext中匯入excel嘗試通過了兩種方法。 需求:匯入excel 在Ext grid中顯示 然後點選按鈕確定是否儲存(後臺做資料驗證,固定列名) 分析需求

    tp3.2和Bootstrap模態框匯入excel表格資料

    匯入按鈕 <button class="btn btn-info" type="button" id="import" data-toggle="modal" data-target="#myModal">匯入</button> 模態框 <!-- Modal

    vue使用js-xlsx外掛匯入Excel表格資料

    import Vue from 'vue' import XLSX from 'xlsx' /** * 匯入ex表格 得到json資料 * 已注入所有Vue例項, * template模板裡呼叫 $importf * 元件方法裡呼叫 this.$importf * 例:<input

    mysql匯入excel表格資料時出錯的解決

    1:匯入的是Excel2007表格格式的資料。 2: 報錯以後資料加進去了。(選擇了錯誤繼續執行) 3:這個錯誤對我的資料有影響嗎? 4:造成這個錯誤的原因是什麼 5:這個是日誌檔案 [2012-07-11 13:57:48] [Msg] Import start [2012-07-11 13:57:48

    MySQL--匯入Excel表格資料

    首先我需要兩個軟體,一個MySQL,一個Navicat for MySQL ;;網上都有,隨便下載 ① 開啟Navicat for MySQL,連線,連線名隨你心情起,你開心就好

    tp3.2excel表格資料匯入資料庫

    第一步:將壓縮包PHPExcel解壓後放到./ThinkPHP/Library/Vendor目錄下面。 第二步:控制器裡面的方法:         public function addActivitydo(){             if (!empty($_FILE

    tp5匯入帶圖片的excel表格資料

    控制器裡:  /**     * 訂單匯入(excel匯入)     */    public function import()    {      &nb

    PHP批量匯入excel資料資料庫簡易版方法(From Jeskitt)

    //常用方法是結合PHPExcel外掛來實現excel資料到資料庫的批量插入,而這裡介紹的是另外一種簡易又靈活方法來實現。 1、首先把要處理的excel文件的資料複製下來,到txt文字中儲存 2、實現程式碼 public function excelIn

    Excel表格資料匯入到SQLServer資料庫

    資料探勘課上,老師說我們最後考察是以課程論文的形式給出,用SQLServer分析資料。 資料探勘用的是Clement軟體,結課寫論文還要用SQLServer分析資料,我們分析的資料肯定不會少,是一點一

    JAVA POI批量匯入EXCEL資料資料庫

    首先先記錄下碰到的問題: 原先想直接傳要上傳的檔案路徑到後端,然後後端絕對定位到相應檔案進行資料的解析,後面發現瀏覽器這邊為了安全問題,是不能獲得檔案的真實路徑的,只能獲得一個虛假的路徑,然後這種做法就行不通了,我的解決方法是先把檔案上傳的到後端相關目錄,解析完資料後在將對應

    如何把EXCEL資料匯入到SQL SERVER資料庫

    在我們完成一個專案開發之後,通常我們需要把客戶的很多資料匯入到資料庫中,面對大量的資料匯入工作,人工匯入肯定是不現實,但是這些又是不得不完成的工作,怎麼辦呢?我們可以利用資料庫管理工具提供的資料匯入的功能即可。我們這裡以SQL SERVE2008為例。SQLSERVER2

    java批量匯入Excel資料資料庫

    public class ImportFile { /** * @param cell 一個單元格的物件 * @return 返回該單元格相應的型別的值 */ public static String getRightTypeCell(

    在java匯入excel表格讀取Excel資料的日期格式

    在ExcelReader類中.getStringCellValue()方法裡: public static String getStringCellValue(Cell cell) { if(cell == null){ return ""; } String strCell = ""; switch (c

    JavaExcel表格資料匯入和匯出步驟和方法

    Java Excel API既可以從本地檔案系統的一個檔案(.xls),也可以從輸入流中讀取Excel資料表。讀取Excel資料表的第一步是建立Workbook(術 語:工作薄),下面的程式碼片段舉例說明了應該如何操作:(完整程式碼見ExcelReading.java)

    匯入Excel表格持久化到資料庫

    頁面按鈕 <form style="overflow:hidden;float:left" enctype="multipart/form-data" id="formSumbit" action="${c

    C#做的一個在vs2010匯入Excel表格的功能

    一:練習時發現問題   在vs除錯的時候一遍一遍輸入資料十分的麻煩,資料多的話每除錯一次就要輸入一次資料,十分的浪費時間,所以做成一個小功能可以將資料直接匯入,節省時間。 二:過程       1.插入一個dataGridview 控制元件                       2.插入並設定MenuS

    JAVA處理Excel表格資料並寫入資料庫

            Excel提供了把SQLServer作為資料來源匯入資料的技術,但似乎沒有提供方法把Excel中的資料匯入到資料庫。Apache的POI提供了Java程式對Microsoft Office格式檔案讀和寫的功能。 基本功能: