java程序导数据
在数据库之间或者excel与数据库之间导数据有时候会遇到需要java代码来实现,下面就是一个熊小demo 记录一下excel与数据库交互,其中用到了
poi:
step1:创建一个pojo用来对应数据库中的表;
step2:编写读取excel的方法:
package sh_excel2db;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import com.datamigration.dmr.sh.model.CpSq;
/**
* TODO 此处描写类的信息
*
* @time Jan 15, 2016 11:23:03 AM
* @author cuixx
* @since JDK1.7
*/
public class util {
public static final Map<String, Integer> PURID2TYPE_MAPPING = new HashMap<String, Integer>();
//这是对一些数据中文对应数字的替换
static {
PURID2TYPE_MAPPING.put("主任信箱",10);
PURID2TYPE_MAPPING.put("咨询",12);
PURID2TYPE_MAPPING.put("投诉",2);
PURID2TYPE_MAPPING.put("其他",4);
}
//这是从excel中读取的数据封装到pojo中,返回list filename为excel地址,sheetName为工作薄名称
public static List<CpSq> getSqList(String fileName, String sheetName) throws Exception {
File file = new File(fileName);
InputStream inputStream = new FileInputStream(file);
POIFSFileSystem poiFSFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook workbook = new HSSFWorkbook(poiFSFileSystem);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum();
HSSFRow row = null;
//一行有多少个单元格
String[] cellsValue = new String[55];
List<CpSq> sqList = new ArrayList<CpSq>();
//这里需要注意行是不是从标题开始循环的
for (int i = 0; i <rowNum; i++) {
row = sheet.getRow(i+1);
for (int j = 0; j < cellsValue.length; j++) {
cellsValue[j] = format(row.getCell(j+1));
}
//pojo
CpSq sq=new CpSq();
sq.setSq_realname(cellsValue[7]);
sq.setModel_id(1);
sq.setPublish_status(1);
sq.setIs_open(0);
sq.setPur_id(PURID2TYPE_MAPPING.get(cellsValue[4]));
sq.setSq_address(cellsValue[6]);
sq.setSq_email(cellsValue[10]);
sq.setSq_phone(cellsValue[8]);
sq.setSq_dtime(cellsValue[3]);
System.out.println(cellsValue[2]+"#####"+cellsValue[3]+"#####"+cellsValue[4]);
sq.setSq_title(cellsValue[46]);
sq.setSq_title2(sq.getSq_title());
sq.setSq_content(cellsValue[47]);
sq.setSq_content2(sq.getSq_content());
sq.setSq_reply(cellsValue[52]);
sqList.add(sq);
}
inputStream.close();
return sqList;
}
public static String format(HSSFCell cell) {
String result = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
result = "";
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_BOOLEAN:
result = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
DecimalFormat formatter = new DecimalFormat("#");
result = formatter.format(cell.getNumericCellValue());
default:
break;
}
return result;
}
public static void outFile(StringBuffer content) {
File file = new File("E:\\SH_Data.sql");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import com.datamigration.dmr.sh.model.CpSq;
/**
* TODO 此处描写类的信息
*
* @time Jan 15, 2016 11:23:03 AM
* @author cuixx
* @since JDK1.7
*/
public class util {
public static final Map<String, Integer> PURID2TYPE_MAPPING = new HashMap<String, Integer>();
//这是对一些数据中文对应数字的替换
static {
PURID2TYPE_MAPPING.put("主任信箱",10);
PURID2TYPE_MAPPING.put("咨询",12);
PURID2TYPE_MAPPING.put("投诉",2);
PURID2TYPE_MAPPING.put("其他",4);
}
//这是从excel中读取的数据封装到pojo中,返回list filename为excel地址,sheetName为工作薄名称
public static List<CpSq> getSqList(String fileName, String sheetName) throws Exception {
File file = new File(fileName);
InputStream inputStream = new FileInputStream(file);
POIFSFileSystem poiFSFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook workbook = new HSSFWorkbook(poiFSFileSystem);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum();
HSSFRow row = null;
//一行有多少个单元格
String[] cellsValue = new String[55];
List<CpSq> sqList = new ArrayList<CpSq>();
//这里需要注意行是不是从标题开始循环的
for (int i = 0; i <rowNum; i++) {
row = sheet.getRow(i+1);
for (int j = 0; j < cellsValue.length; j++) {
cellsValue[j] = format(row.getCell(j+1));
}
//pojo
CpSq sq=new CpSq();
sq.setSq_realname(cellsValue[7]);
sq.setModel_id(1);
sq.setPublish_status(1);
sq.setIs_open(0);
sq.setPur_id(PURID2TYPE_MAPPING.get(cellsValue[4]));
sq.setSq_address(cellsValue[6]);
sq.setSq_email(cellsValue[10]);
sq.setSq_phone(cellsValue[8]);
sq.setSq_dtime(cellsValue[3]);
System.out.println(cellsValue[2]+"#####"+cellsValue[3]+"#####"+cellsValue[4]);
sq.setSq_title(cellsValue[46]);
sq.setSq_title2(sq.getSq_title());
sq.setSq_content(cellsValue[47]);
sq.setSq_content2(sq.getSq_content());
sq.setSq_reply(cellsValue[52]);
sqList.add(sq);
}
inputStream.close();
return sqList;
}
public static String format(HSSFCell cell) {
String result = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
result = "";
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_BOOLEAN:
result = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
DecimalFormat formatter = new DecimalFormat("#");
result = formatter.format(cell.getNumericCellValue());
default:
break;
}
return result;
}
public static void outFile(StringBuffer content) {
File file = new File("E:\\SH_Data.sql");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//测试用的
public static void main(String args[]) throws Exception {
List list=getSqList("E:\\test.xls","SQL Results");
}
}
public static void main(String args[]) throws Exception {
List list=getSqList("E:\\test.xls","SQL Results");
}
}
//插入数据库
package sh_excel2db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import com.datamigration.core.db.DB;
import com.datamigration.dmr.sh.model.CpSq;
/**
* TODO 此处描写类的信息
*
* @time Jan 15, 2016 11:53:42 AM
* @author cuixx
* @since JDK1.7
*/
public class objectList2Db {
public static final String engine = "shtar";
public static void insertList(List<CpSq> list) throws Exception{
DB db = DB.getInstance(engine);
PreparedStatement prepstmt = null;
ResultSet rs = null;
db.connect();
StringBuffer bff=new StringBuffer();
String insert_sql="insert into cp_sq(sq_id,sq_realname,sq_address,sq_email,sq_phone,sq_dtime,sq_title,sq_title2,sq_content,sq_content2,sq_reply,model_id,pur_id,publish_status,is_open) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Connection conn=db.getCon();
prepstmt = conn.prepareStatement(insert_sql);
Iterator itr=list.iterator();
int count=0;
while(itr.hasNext()) {
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import com.datamigration.core.db.DB;
import com.datamigration.dmr.sh.model.CpSq;
/**
* TODO 此处描写类的信息
*
* @time Jan 15, 2016 11:53:42 AM
* @author cuixx
* @since JDK1.7
*/
public class objectList2Db {
public static final String engine = "shtar";
public static void insertList(List<CpSq> list) throws Exception{
DB db = DB.getInstance(engine);
PreparedStatement prepstmt = null;
ResultSet rs = null;
db.connect();
StringBuffer bff=new StringBuffer();
String insert_sql="insert into cp_sq(sq_id,sq_realname,sq_address,sq_email,sq_phone,sq_dtime,sq_title,sq_title2,sq_content,sq_content2,sq_reply,model_id,pur_id,publish_status,is_open) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Connection conn=db.getCon();
prepstmt = conn.prepareStatement(insert_sql);
Iterator itr=list.iterator();
int count=0;
while(itr.hasNext()) {
/ /这个用来把sql语句打印到文件中
bff.append("insert into cp_sq(sq_id,sq_realname,sq_address,sq_email,sq_phone,sq_dtime,sq_title,sq_title2,sq_content,sq_content2,sq_reply) values(");
CpSq sq =(CpSq)itr.next();
prepstmt.setInt(1, 7600+count);
bff.append(String.valueOf(7600+count)+",");
prepstmt.setString(2, sq.getSq_realname());
bff.append("'"+sq.getSq_realname()+"'"+",");
prepstmt.setString(3, sq.getSq_address());
bff.append("'"+sq.getSq_address()+"'"+",");
prepstmt.setString(4, sq.getSq_email());
bff.append("'"+sq.getSq_email()+"'"+",");
prepstmt.setString(5, sq.getSq_phone());
bff.append("'"+sq.getSq_phone()+"'"+",");
prepstmt.setString(6, sq.getSq_dtime());
bff.append("'"+sq.getSq_dtime()+"'"+",");
prepstmt.setString(7, sq.getSq_title());
bff.append("'"+sq.getSq_title()+"'"+",");
prepstmt.setString(8, sq.getSq_title2());
bff.append("'"+sq.getSq_title2()+"'"+",");
prepstmt.setString(9, sq.getSq_content());
bff.append("'"+sq.getSq_content()+"'"+",");
prepstmt.setString(10, sq.getSq_content2());
bff.append("'"+sq.getSq_content2()+"'"+",");
prepstmt.setString(11, sq.getSq_reply());
bff.append("'"+sq.getSq_reply()+"');"+"\r\n");
prepstmt.setInt(12, sq.getModel_id());
bff.append(String.valueOf(sq.getModel_id())+",");
prepstmt.setInt(13, sq.getPur_id());
bff.append(String.valueOf(sq.getPur_id())+",");
prepstmt.setInt(14, sq.getPublish_status());
bff.append(String.valueOf(sq.getPublish_status())+",");
prepstmt.setInt(15, sq.getIs_open());
bff.append(String.valueOf(sq.getIs_open())+",");
int num=prepstmt.executeUpdate();
count++;
}
util.outFile(bff);
db.close();
}
public static void main(String[] args) throws Exception {
List<CpSq> list=util.getSqList("E:\\test.xls","SQL Results");
insertList(list);
System.out.print(list.size());
}
}
bff.append("insert into cp_sq(sq_id,sq_realname,sq_address,sq_email,sq_phone,sq_dtime,sq_title,sq_title2,sq_content,sq_content2,sq_reply) values(");
CpSq sq =(CpSq)itr.next();
prepstmt.setInt(1, 7600+count);
bff.append(String.valueOf(7600+count)+",");
prepstmt.setString(2, sq.getSq_realname());
bff.append("'"+sq.getSq_realname()+"'"+",");
prepstmt.setString(3, sq.getSq_address());
bff.append("'"+sq.getSq_address()+"'"+",");
prepstmt.setString(4, sq.getSq_email());
bff.append("'"+sq.getSq_email()+"'"+",");
prepstmt.setString(5, sq.getSq_phone());
bff.append("'"+sq.getSq_phone()+"'"+",");
prepstmt.setString(6, sq.getSq_dtime());
bff.append("'"+sq.getSq_dtime()+"'"+",");
prepstmt.setString(7, sq.getSq_title());
bff.append("'"+sq.getSq_title()+"'"+",");
prepstmt.setString(8, sq.getSq_title2());
bff.append("'"+sq.getSq_title2()+"'"+",");
prepstmt.setString(9, sq.getSq_content());
bff.append("'"+sq.getSq_content()+"'"+",");
prepstmt.setString(10, sq.getSq_content2());
bff.append("'"+sq.getSq_content2()+"'"+",");
prepstmt.setString(11, sq.getSq_reply());
bff.append("'"+sq.getSq_reply()+"');"+"\r\n");
prepstmt.setInt(12, sq.getModel_id());
bff.append(String.valueOf(sq.getModel_id())+",");
prepstmt.setInt(13, sq.getPur_id());
bff.append(String.valueOf(sq.getPur_id())+",");
prepstmt.setInt(14, sq.getPublish_status());
bff.append(String.valueOf(sq.getPublish_status())+",");
prepstmt.setInt(15, sq.getIs_open());
bff.append(String.valueOf(sq.getIs_open())+",");
int num=prepstmt.executeUpdate();
count++;
}
util.outFile(bff);
db.close();
}
public static void main(String[] args) throws Exception {
List<CpSq> list=util.getSqList("E:\\test.xls","SQL Results");
insertList(list);
System.out.print(list.size());
}
}
//下面为jDB的内容
package com.datamigration.core.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DB {
private static String driver;
private static String url;
private static String user;
private static String password;
private static DB db;
private Connection con = null;
private Statement st = null;
private String engine;
public final static DB getInstance(String engine) throws Exception {
db = new DB();
db.engine = engine;
Properties pro = new Properties();
pro.load(DB.class.getResourceAsStream("/jdbc.properties"));
driver = pro.getProperty(engine + ".driver");
url = pro.getProperty(engine + ".url");
user = pro.getProperty(engine + ".user");
password = pro.getProperty(engine + ".password");
return db;
}
public void connect() throws Exception {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
}
public ResultSet query(String sql) throws Exception {
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
return rs;
}
public int update(String sql) throws Exception {
st = con.createStatement();
int r = st.executeUpdate(sql);
return r;
}
public void commit() throws Exception {
con.commit();
}
public void rollback() throws Exception {
con.rollback();
}
public void close() throws Exception {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
public Connection getCon() {
return con;
}
public String getEngine() {
return engine;
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DB {
private static String driver;
private static String url;
private static String user;
private static String password;
private static DB db;
private Connection con = null;
private Statement st = null;
private String engine;
public final static DB getInstance(String engine) throws Exception {
db = new DB();
db.engine = engine;
Properties pro = new Properties();
pro.load(DB.class.getResourceAsStream("/jdbc.properties"));
driver = pro.getProperty(engine + ".driver");
url = pro.getProperty(engine + ".url");
user = pro.getProperty(engine + ".user");
password = pro.getProperty(engine + ".password");
return db;
}
public void connect() throws Exception {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
}
public ResultSet query(String sql) throws Exception {
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
return rs;
}
public int update(String sql) throws Exception {
st = con.createStatement();
int r = st.executeUpdate(sql);
return r;
}
public void commit() throws Exception {
con.commit();
}
public void rollback() throws Exception {
con.rollback();
}
public void close() throws Exception {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
public Connection getCon() {
return con;
}
public String getEngine() {
return engine;
}
}
//下面为jdbc的内容
# SH MySQL
shtar.driver=com.mysql.jdbc.Driver
shtar.url=jdbc:mysql://xxx.xxx.70.130:1103/cicro?characterEncoding=UTF-8
shtar.user=root
shtar.password=mysql
shtar.driver=com.mysql.jdbc.Driver
shtar.url=jdbc:mysql://xxx.xxx.70.130:1103/cicro?characterEncoding=UTF-8
shtar.user=root
shtar.password=mysql