Use jdbc to read and write excel files under windows

There are countless ways to use java to read and write excel. Here we treat the excel file as a database and use the jdbc connection to read and write it. Again, existence is reasonable. Each method of reading and writing excel has its advantages and disadvantages, its emphasis, and its application scenarios. Mastering one more method may mean one more choice, and it may be that this solution is the best in some scenarios. Of course, if you are diligent in discovery, you will see more benefits if you are good at discovery. jdbc has already become a standard, precisely because it is a standard, so if you master this standard, it means that you can learn this kind of thing with the smallest learning cost. For example, if you can only write sql or are good at writing sql, then using sql to solve problems may get twice the result with half the effort. After all, it is somewhat uncomfortable to use something that I am not good at. There are still some restrictions on using sql to read and write excel under windows. For example, the program should preferably be 32-bit, and the support for sql syntax is relatively weak.

1), taking jdk1.8 32-bit as an example, the following code implements operations such as query, insertion, and modification of excel files (.xlsx)

package com.lbz; 

import sun.jdbc.odbc.JdbcOdbcDatabaseMetaData; 

import java.lang.reflect.Field; 
import java.sql.*; 
import java.util.*; 

public class Excel{ 
    private Connection connection; 
    public Excel(){ 
        try { 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
            //Pay attention to 32-bit system and 64-bit system, only 32-bit system can be used here 
            String path = System.getProperty("excelfilepath"); 
            boolean useXlsOnly = false; 
            String url = "jdbc:odbc:driver={Microsoft Excel Driver (*.xls)};READONLY=false;DBQ="+path;; url = "  
            if(!useXlsOnly){
                jdbc:odbc:Driver={Microsoft Excel Driver (*. xls, *.xlsx, *.xlsm, *.xlsb)};READONLY=false;DBQ="+path; 
            ( 

            ) ; 
            prop.put("charSet","gbk"); 
            prop.put("user",""); 
            prop.put("password",""); 
            Connection con = null; 
            try { 
                con = DriverManager.getConnection (url, prop);//When there is no username and password, it is directly empty 
                JdbcOdbcDatabaseMetaData meta = (JdbcOdbcDatabaseMetaData) con.getMetaData(); 
                ResultSet resultSet = meta.getTables(null,null,null,null);
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
 
                List<String> tables = new ArrayList<String>() ; 
                while(resultSet.next()){ 
                    String tableName = resultSet.getString(3); 
                    tables.add(tableName); 
                }
                System.out.println(tables);

                //System.out.println(meta.getStringFunctions());
                //System.out.println(meta.getNumericFunctions());
                //System.out.println(meta.getTimeDateFunctions());
            }catch (Exception exc){
                exc.printStackTrace();
            }
            this.connection = con;
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public Excel insert(String sql) {
        Statement statement = null;
        try {
            statement = this.connection.createStatement();
            statement.executeUpdate(sql);

            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return this;
    }

    public Excel update(String sql) {
        Statement statement = null;
        try {
            statement = this.connection.createStatement();
            statement.executeUpdate(sql);

            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return this;
    }

    public <T> List<T> select(String sql,Class c) {
        Statement statement = null;
        List<T> list = new ArrayList<T>();
        try {
            statement = this.connection.createStatement();
            ResultSet result = statement.executeQuery(sql);
            Field[] flds = c.getDeclaredFields();
            while (result.next()) {
                T t = (T)c.newInstance();
                for(Field f : flds){
                    if("id".equals(f.getName())){
                        continue;
                    }
                    f.setAccessible(true);
                    f.set(t,result.getString(f.getName()));
                }
                list.add(t);
            }
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        return list;
    }

    public Excel ddl(String sql){
        Statement statement = null;
        try {
            statement = this.connection.createStatement();
            statement.executeUpdate(sql);

            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return this;
    }


    public List<Map> selectMap(String sql) {
        Statement statement = null;
        List<Map> list = new ArrayList<>();
        try {
            statement = this.connection.createStatement();
            ResultSet result = statement.executeQuery(sql);
            ResultSetMetaData metaData = result.getMetaData();
            List<String> colList= new ArrayList<>();
            for(int i=0;i<metaData.getColumnCount();i++){
                String colName = metaData.getColumnName(i + 1);
                colList.add(colName);
            }

            while (result.next()) {
                Map<String,String> map = new HashMap<>();
                for(int i = 0;i<colList.size();i++){
                    String colName = colList.get(i);
                    Object v = result.getObject(colName);
                    if(v == null || "null".equals(v)){
                        v = "";
                    }
                    map.put(colName,String.valueOf(v));
                }
                list.add(map);
            }

            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }


    public void releaseConnection(){
        try{
            this.connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args){
        System.setProperty("excelfilepath","E:/git/StoreHouseEnv/lib/test.xlsx");

        Excel excel = new Excel();
        List<Map> list = excel.selectMap("select * from [Sheet1$]");
        System.out.println(list);
        list = excel.selectMap("select max(len(NAME)) as namelength from [Sheet1$]");
        System.out.println(list);

        for(int i=0;i<5;i++){
            excel.insert("insert into [Sheet1$](ID,NAME) values('222','测试插入')");
        }
        excel.update("update [Sheet1$] set name='pingping'");
        list = excel.selectMap("select max(len(NAME)) as namelength from [Sheet1$]");
        System.out.println(list);
        excel.releaseConnection();
    }
}

2. odbc data source

Many odbc data sources only support 32-bit, such as our commonly used oracle database, in jdbc we generally use the "thin" method to connect, or use odbc to connect, if you use odbc to connect, you usually find 32-bit. The odbc data source can be viewed in the control panel.

The database connection string in the code is

jdbc:odbc:Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};READONLY=false;

The Excel data source here needs to be adjusted according to the actual situation, and manual installation may be required. readonly=false means the excel file can be written, readonly=true means read-only.

The connection string of other office products such as access database is basically similar to that of excel, just modify the corresponding odbc data source.

3. The problem of jdk version

There is basically no problem running the above code with jdk1.7 32-bit version, but some extra work is required to use jdk1.8 32-bit version.

Find jre\lib\rt.jar under jdk1.7 and extract some folders

Because the rt.jar file itself is relatively large, not all of them are decompressed, so use the jar command in the above figure to decompress some directories

sun\jdbc和sun\security\action

 Because jdk1.8 does not have these directories, these directories are extracted and labeled as an additional jar package for reference. Of course, it can also be referenced without the jar package.

Use the jar cvf sunjdbcodbc.jar sun command to package the sun directory into a jar package

In addition to referencing the above classes, you also need to copy the JdbcOdbc.dll in the jdk1.7 installation directory to the same structure directory of jdk1.8, of course, you can also load it in other ways.

 4. Running results

Guess you like

Origin blog.csdn.net/weixin_38526093/article/details/124558246