Java將xlsx或者xls數據讀入SQLite數據庫

做大創過程中需要將大量Excel數據讀入SQLite數據庫,百度了很多,但並沒有解決我的問題,摸索了一天,想出了一個稍顯複雜的辦法:

第一步:將xlsx或者xls文件另存爲csv文件(注意不能直接修改後綴),如果文件有很多,可以用Excel的宏來批量轉換,代碼如下:

Sub SaveToCSVs()

    Dim fDir As String

    Dim wB As Workbook

    Dim wS As Worksheet

    Dim fPath As String

    Dim sPath As String

    fPath = "F:\xxx\xxx\"      //存放Excel文件的文件夾

    sPath = "F:\xxx\CSV\"     //將批量轉換生成的CSV文件存入sPath文件夾下

    fDir = Dir(fPath)

    Do While (fDir <> "")

        If Right(fDir, 4) = ".xls" Or Right(fDir, 5) = ".xlsx" Then

            On Error Resume Next

            Set wB = Workbooks.Open(fPath & fDir)

            'MsgBox (wB.Name)

            For Each wS In wB.Sheets

                wS.SaveAs sPath & wB.Name & ".csv", xlCSV

            Next wS

            wB.Close False

            Set wB = Nothing

        End If

        fDir = Dir

        On Error GoTo 0

    Loop

End Sub

第二步:將CSV文件的編碼方式修改爲UTF-8,推薦用EditPlus批量修改文件編碼方式,具體操作步驟後續補充。

第三步,利用Java修改CSV文件後綴爲txt,代碼如下:

package 大創數據導入;

/** 
 * @ClassName: ChangeSuffix
 * @description: 
 * @author: Cyril_KI
 * @Date: 2020年4月26日 上午10:24:55
 */


import java.io.File;
import java.util.Scanner;

public class ChangeSuffix {
	static String path;
	static String from,to;
	public ChangeSuffix(String path,String from,String to) {
		// TODO 自動生成的構造函數存根
		this.path=path;
		this.from=from;
		this.to=to;
	}
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入要修改文件後綴名的文件夾:");
        String path = sc.nextLine();
        System.out.println("請輸入修改前的後綴名:");
        //String from = "csv";
        System.out.println("請輸入修改後的後綴名:");
        //String to = "txt";

        reName(path, from, to);
        System.out.println("全部修改完成!!!");
    }

    public static void reName(String path, String from, String to) {
        File f = new File(path);
        File[] fs = f.listFiles();
        for (File subFile : fs) {
            // 如果文件是文件夾則遞歸調用批量更改文件後綴名的函數
            if (subFile.isDirectory()) {
                reName(subFile.getPath(), from, to);
            } else {
                String name = subFile.getName();
                if (name.endsWith(from)) {

                    subFile.renameTo(new File(subFile.getParent() + "/" + name.substring(0, name.indexOf(from)) + to));
                }
            }
        }
    }

}

第四步:讀取txt文件存入SQLite數據庫,代碼後續補充。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章