如何用java导入Excel数据到数据库

2024-10-28 04:23:19
推荐回答(2个)
回答(1):

参考下面代码:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class WriteExcel {

WritableWorkbook book=null;

public void OutputExcel(ArrayList arlist,String Path){
try{
book = Workbook.createWorkbook(new File(Path));
//设置表名
WritableSheet sheet = book.createSheet("考试单",0);
//生成表格题头
Label labe1 = new Label(0, 0, "考生姓名" );
Label labe2 = new Label(1, 0, "地区");
Label labe3 = new Label(2, 0, "所属院校");
Label labe4 = new Label(3, 0, "班级");
Label labe5 = new Label(4, 0, "考试号");
Label labe6 = new Label(5, 0, "考试时间");
Label labe7 = new Label(6, 0, "科目名称");

//将生成的单元格添加到工作表中
sheet.addCell(labe1);
sheet.addCell(labe2);
sheet.addCell(labe3);
sheet.addCell(labe4);
sheet.addCell(labe5);
sheet.addCell(labe6);
sheet.addCell(labe7);

Iterator it = arlist.iterator();
int i = 1;

while(it.hasNext()){
//通过迭代获得arlist里的MarkesData对象
MarkesData temp = (MarkesData)it.next();

//取得数据生成单元格
Label label1=new Label(0,i,temp.getUser_name());
Label label2=new Label(1,i,temp.getArea_name());
Label label3=new Label(2,i,temp.getCollege_name());
Label label4=new Label(3,i,temp.getClass_name());
Label label5=new Label(4,i,temp.getTest_name());
Label label6=new Label(5,i,temp.getStarttime());
Label label7=new Label(6,i,temp.getSubject_name());

//将生成的单元格添加到工作表中
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
sheet.addCell(label4);
sheet.addCell(label5);
sheet.addCell(label6);
sheet.addCell(label7);

i++;
}
book.write();
book.close();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
if(book!=null)book.close();
}catch(Exception e){
System.out.println("exception when closing Connection in finally");
System.out.println(e.getMessage().toString());
}
}
}
}

回答(2):

你是怎么样用JAVA从EXCEL中取得数据不了解?

导入数据库,就是从EXCEL中取得数据,
然后生成INSERT语句,向数据库中插入数据。