Java实现把excel xls中数据转为可直接插入数据库的sql文件
我的一贯风格,代码说明一切。。
废话不多说了,直接给大家贴代码了,具体代码如下所示:
packageTools;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.lang.reflect.Field;
importjava.util.ArrayList;
importjava.util.List;
importjxl.Sheet;
importjxl.Workbook;
importentity.Student;
publicclassConvertXMSToSQL{
/**
*从xls表格中获取数据,生成可执行的sql文件,用以插入数据库,注意需要引入jxl包!支持int,Integer,long,Long,String
*,可自行扩展
*
*@paramargs
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*/
publicstaticvoidmain(String[]args)throwsIllegalArgumentException,
IllegalAccessException{
//得到表格中所有的数据
List<Student>listExcel=getAllByExcel("C:\\Users\\xxx\\Desktop\\zzz.xls");
try{
Stringpath="C:\\Users\\xxx\\Desktop\\convert.sql";//文件保存路径、名字
Filefile=newFile(path);
BufferedWriterow=newBufferedWriter(newFileWriter(file));
for(Studentc:listExcel){
Stringsql="insertintocfg_avatarvalues("+outSql(c)
+")";
ow.write(sql+";"+"\n");
}//写入内容
ow.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*从xls中获取数据
*
*@paramfile
*@return
*/
publicstaticList<Student>getAllByExcel(Stringfile){
List<Student>list=newArrayList<Student>();
try{
Workbookrwb=Workbook.getWorkbook(newFile(file));
Sheetrs=rwb.getSheet(0);
intclos=rs.getColumns();//得到所有的列
introws=rs.getRows();//得到所有的行
//样例中,数据从第三列第一行开始
for(inti=2;i<rows;i++){
//取得的每一行的所有数据存入listString
List<String>listString=newArrayList<String>();
for(intj=0;j<clos;j++){
Stringstr=rs.getCell(j,i).getContents();
listString.add(str);
}
StudentStudent=(Student)newObject(newStudent(),listString);
list.add(Student);
}
}catch(Exceptione){
e.printStackTrace();
}
returnlist;
}
/**
*使用反射设置数据。此例中可设置的数据类型有限,没有的请自己添加!!!
*
*@paramobj
*@paramlist
*@return
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*/
publicstaticObjectnewObject(Objectobj,List<String>list)
throwsIllegalArgumentException,IllegalAccessException{
Field[]field=obj.getClass().getDeclaredFields();
for(inti=0;i<field.length;i++){
Fieldf=field[i];
f.setAccessible(true);
if(f.getType()==String.class){
f.set(obj,list.get(i));
}
if(f.getType()==Integer.class){
f.set(obj,Integer.parseInt(list.get(i)));
}
if(f.getType()==int.class){
f.set(obj,Integer.parseInt(list.get(i)));
}
if(f.getType()==Long.class){
f.set(obj,Long.parseLong(list.get(i)));
}
if(f.getType()==long.class){
f.set(obj,Long.parseLong(list.get(i)));
}
}
returnobj;
}
/**
*
*@paramobj
*@return
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*/
publicstaticStringoutSql(Objectobj)throwsIllegalArgumentException,
IllegalAccessException{
StringBufferbuffer=newStringBuffer();
Field[]field=obj.getClass().getDeclaredFields();
for(inti=0;i<field.length;i++){
Fieldf=field[i];
f.setAccessible(true);
if(f.getType()==String.class){
buffer.append("'");
}
buffer.append(f.get(obj));
if(f.getType()==String.class){
buffer.append("'");
}
if(i<field.length-1){
buffer.append(",");
}
}
returnbuffer.toString();
}
}
有关Java实现把excelxls中数据转为可直接插入数据库的sql文件的知识,小编就给大家介绍这么多,希望对大家有所帮助!