乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > java中怎么把excel中的数据存储到数据库中-java从excel导入数据,java excel导入数据到数据库

java中怎么把excel中的数据存储到数据库中-java从excel导入数据,java excel导入数据到数据库

作者:乔山办公网日期:

返回目录:excel表格制作


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jxl.*;
public class SimUpdate {
private String fileName;
public ZfzSimUpdate(String fileName){
this.fileName = fileName;
}
static Map tNames;
static{
tNames = new HashMap();
}
/**
* 用于产生 数据库的 ID 值,组成 [年月日时分秒(100-999)] 总共 17 位数.
* 根据不同的表名,可保证同一秒内产生的 ID 号不重复
*/
private static String getDtime() {
String rid;
Date nd = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
rid = sdf.format(nd);
return rid;
}

public String getSeqNumber(String tableName) {
if(tableName == null || "".equals(tableName))
tableName = "GENERY";
Integer it;
// noinspection SynchronizeOnNonFinalField
synchronized(tNames){
it = (Integer)tNames.get(tableName);
if(it == null){
it = new Integer(100);
tNames.put(tableName, it);
}else{
if(it.intValue() > 998)
it = new Integer(100);
else
it = new Integer(1 + it.intValue());
tNames.put(tableName, it);
}
}
return getDtime() + String.valueOf(it);
}

private void updateDb(){
try{
Connection conn = DbPool.connectDB();
if(conn != null){
Statement stmt = conn.createStatement();
/**********************************************/
jxl.Workbook rwb = null;
try{
//构建e68a847a64363Workbook对象 只读Workbook对象
//直接从本地文件创建Workbook
//从输入流创建Workbook
InputStream is = new FileInputStream(fileName);
rwb = Workbook.getWorkbook(is);
//Sheet(术语:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中
//Sheet的下标是从0开始的
//获取第一张Sheet表
Sheet rs = rwb.getSheet(0);
//获取Sheet表中所包含的总列数
int rsColumns = rs.getColumns();
//获取Sheet表中所包含的总行数
int rsRows = rs.getRows();
//获取指这下单元格的对象引用

String simNumber = "",termSeqId = "";
//指定SIM卡号及序列号
for(int i=0;i<rsRows;i++){
for(int j=0;j<rsColumns;j++){
Cell cell = rs.getCell(j,i);
if(j==0){
simNumber = cell.getContents();
}
termSeqId = "633"+simNumber;
}
String sql = "查询SQL";
int isOk = stmt.executeUpdate(sql);
if(isOk == 0 && !simNumber.equals("")){
String termId = getSeqNumber("termInf");
String insertSql = "自定义INSERT";
int isAdd = stmt.executeUpdate(insertSql);
if(isAdd > 0){
System.out.println("成功插入第"+i+"条数据");
}

}
//System.out.println("SIM卡号:"+simNumber+",序列号:"+termSeqId);
}

//以下代码为写入新的EXCEL,这里不使用,所以注释
/*

//利用已经创建的Excel工作薄创建新的可写入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("D://Book2.xls"),rwb);
//读取第一张工作表
jxl.write.WritableSheet ws = wwb.getSheet(0);

//获取第一个单元格对象
jxl.write.WritableCell wc = ws.getWritableCell(0, 0);
//决断单元格的类型,做出相应的转化
if (wc.getType() == CellType.LABEL) {
Label l = (Label) wc;
l.setString("The value has been modified.");
}
//写入Excel对象
wwb.write();
wwb.close();
*/
}catch(Exception e){
e.printStackTrace();
}
finally{
//操作完成时,关闭对象,翻译占用的内存空间
rwb.close();

}
/*********************************************/

}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
DbPool dbPool = new DbPool("dbConn.cfg");//连接数据库
SimUpdate simUpdate = new SimUpdate("zfz_sim.xls");
simUpdate.updateDb();

}

}

我只用了读取XLS,写入没试,应该没问题吧,你把注释了的拿 来试一下吧




1、加入依赖的jar文件:

引用:
*mysql的jar文件 
*Spring_HOME/lib/poi/*.jar

2、编写数据库链接类 

package com.zzg.db;  
  
import java.sql.Connection;  
import java.sql.DriverManager;  
  
public class DbUtils {  
    private static Connection conn;  
  
    static {  
        try {  
            Class.forName("com.mysql.jdbc.Driver");  
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static Connection getConn() {  
        return conn;  
    }  
  
    public static void setConn(Connection conn) {  
        DbUtils.conn = conn;  
    }  
}

3、编写数据库操作类 

package com.zzg.db;  
  
import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.SQLException;  
  
public class ExcuteData {  
    private PreparedStatement pstmt;  
    public boolean ExcuData(String sql) {  
        Connection conn = DbUtils.getConn();  
        boolean flag=false;  
        try {  
            pstmt = conn.prepareStatement(sql);  
            flag=pstmt.execute();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }  
}

4、编写Excel表格实体类 

package com.zzg.model;  
  
public class TableCell {  
    private String _name;  
    private String _value;  
  
    public String get_name() {  
        return _name;  
    }  
  
    public void set_name(String _name) {  
        this._name = _name;  
    }  
  
    public String get_value() {  
        return _value;  
    }  
  
    public void set_value(String _value) {  
        this._value = _value;  
    }  
}

5、编写主键生成方法

package com.zzg.util;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Random;  
  
public class GenericUtil {  
    public static String getPrimaryKey()  
    {  
        String primaryKey;  
        primaryKey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());  
        Random r = new Random();  
        primaryKey +=r.nextInt(100000)+100000;  
        return primaryKey;  
    }  
}

6、编写Excel操作类 

package com.zzg.deployData;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.Serializable;  
import java.util.ArrayList;  
import java.util.List;  
import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFRow;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import com.zzg.db.ExcuteData;  
import com.zzg.model.TableCell;  
import com.zzg.util.GenericUtil;  
  
public class OperExcel<T extends Serializable> {  
    private HSSFWorkbook workbook;  
    private String tableName;  
    private Class<T> type;  
    private String sheetName;  
  
    public OperExcel(File excelFile, String tableName, Class<T> type,  
            String sheetName) throws FileNotFoundException,  
            IOException {  
        workbook = new HSSFWorkbook(new FileInputStream(excelFile));  
        this.tableName = tableName;  
        this.type = type;  
        this.sheetName = sheetName;  
        InsertData();  
    }  
  
    // 向表中写入数据  
    public void InsertData() {  
        System.out.println("yyy");  
        ExcuteData excuteData = new ExcuteData();  
        List<List> datas = getDatasInSheet(this.sheetName);  
        // 向表中添加数据之前先删除表中数据  
        String strSql = "delete from " + this.tableName;  
        excuteData.ExcuData(strSql);  
        // 拼接sql语句  
        for (int i = 1; i < datas.size(); i++) {  
            strSql = "insert into " + this.tableName + "(";  
            List row = datas.get(i);  
            for (short n = 0; n < row.size(); n++) {  
                TableCell excel = (TableCell) row.get(n);  
                if (n != row.size() - 1)  
                    strSql += excel.get_name() + ",";  
                else  
                    strSql += excel.get_name() + ")";  
            }  
            strSql += " values (";  
            for (short n = 0; n < row.size(); n++) {  
                TableCell excel = (TableCell) row.get(n);  
                try {  
                    if (n != row.size() - 1) {  
                        strSql += getTypeChangeValue(excel) + ",";  
                    } else  
                        strSql += getTypeChangeValue(excel) + ")";  
                } catch (RuntimeException e) {  
                    e.printStackTrace();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            //执行sql  
            excuteData.ExcuData(strSql);  
        }  
    }  
  
    /** 
     * 获得表中的数据 
     * @param sheetName 表格索引(EXCEL 是多表文档e5a48de588b6e799bee5baa6e997aee7ad94335,所以需要输入表索引号) 
     * @return 由LIST构成的行和表 
     */  
    public List<List> getDatasInSheet(String sheetName) {  
        List<List> result = new ArrayList<List>();  
        // 获得指定的表  
        HSSFSheet sheet = workbook.getSheet(sheetName);  
        // 获得数据总行数  
        int rowCount = sheet.getLastRowNum();  
        if (rowCount < 1) {  
            return result;  
        }  
        // 逐行读取数据  
        for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {  
            // 获得行对象  
            HSSFRow row = sheet.getRow(rowIndex);  
            if (row != null) {  
                List<TableCell> rowData = new ArrayList<TableCell>();  
                // 获得本行中单元格的个数  
                int columnCount = sheet.getRow(0).getLastCellNum();  
                // 获得本行中各单元格中的数据  
                for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) {  
                    HSSFCell cell = row.getCell(columnIndex);  
                    // 获得指定单元格中数据  
                    Object cellStr = this.getCellString(cell);  
                    TableCell TableCell = new TableCell();  
                    TableCell.set_name(getCellString(  
                            sheet.getRow(0).getCell(columnIndex)).toString());  
                    TableCell.set_value(cellStr == null ? "" : cellStr  
                            .toString());  
                    rowData.add(TableCell);  
                }  
                result.add(rowData);  
            }  
        }  
        return result;  
    }  
  
    /** 
     * 获得单元格中的内容 
     *  
     * @param cell 
     * @return result 
     */  
    protected Object getCellString(HSSFCell cell) {  
        Object result = null;  
        if (cell != null) {  
            int cellType = cell.getCellType();  
            switch (cellType) {  
  
            case HSSFCell.CELL_TYPE_STRING:  
                result = cell.getStringCellValue();  
                break;  
            case HSSFCell.CELL_TYPE_NUMERIC:  
                result = cell.getNumericCellValue();  
                break;  
            case HSSFCell.CELL_TYPE_FORMULA:  
                result = cell.getNumericCellValue();  
                break;  
            case HSSFCell.CELL_TYPE_ERROR:  
                result = null;  
                break;  
            case HSSFCell.CELL_TYPE_BOOLEAN:  
                result = cell.getBooleanCellValue();  
                break;  
            case HSSFCell.CELL_TYPE_BLANK:  
                result = null;  
                break;  
            }  
        }  
        return result;  
    }  
  
    // 根据类型返回相应的值  
    @SuppressWarnings("unchecked")  
    public String getTypeChangeValue(TableCell excelElement)  
            throws RuntimeException, Exception {  
        String colName = excelElement.get_name();  
        String colValue = excelElement.get_value();  
        String retValue = "";  
        if (colName.equals("id")) {  
            retValue = "'" + GenericUtil.getPrimaryKey() + "'";  
            return retValue;  
        }  
        if (colName == null) {  
            retValue = null;  
        }  
        if (colName.equals("class_createuser")) {  
            retValue = "yaa101";  
            return "'" + retValue + "'";  
        }  
        retValue = "'" + colValue + "'";  
        return retValue;  
    }  
}

7、编写调用操作Excel类的方法 

package com.zzg.deployData;  
  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
  
public class DeployData {  
    private File fileOut;  
  
    public void excute(String filepath) {  
        fileOut = new File(filepath);  
        this.deployUserInfoData();  
    }  
  
    public void deployUserInfoData() {  
        try {  
            new OperExcel(fileOut, "test", Object.class, "Sheet1");  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

8、编写客户端 

package com.zzg.client;  
  
import com.zzg.deployData.DeployData;  
  
public class DeployClient {  
    public static void main(String[] args) {  
        DeployData deployData = new DeployData();  
        deployData.excute("D://test.xls");  
    }  
}

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网