乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > <em>Java</em> 怎么把 excel文件导入到数据库-java 上传excel到数据库

<em>Java</em> 怎么把 excel文件导入到数据库-java 上传excel到数据库

作者:乔山办公网日期:

返回目录:excel表格制作


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

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

package com.ddns.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.hssf.util.Region;
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2010-6-28
* Time: 10:56:48
* To change this template use File | Settings | File Templates.
*/
public class ExcelFile {
/**
* 新建一个Excel文件,里面添加5行5列的内容,再添加两个高度为2的大单元格7a64e58685e5aeb9364
*
* @param fileName
*/
public void writeExcel(String fileName) {

//目标文件
File file = new File(fileName);
FileOutputStream fOut = null;
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel工作簿中建一工作表,其名为缺省值。
// 也可以指定工作表的名字。
HSSFSheet sheet = workbook.createSheet("Test_Table");

// 创建字体,红色、粗体
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// 创建单元格的格式,如居中、左对齐等
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 水平方向上居中对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 垂直方向上居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 设置字体
cellStyle.setFont(font);

//下面将建立一个4行3列的表。第一行为表头。
int rowNum = 0;//行标
int colNum = 0;//列标
//建立表头信息
// 在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow((short) rowNum);
// 单元格
HSSFCell cell = null;
for (colNum = 0; colNum < 5; colNum++) {
// 在当前行的colNum列上创建单元格
cell = row.createCell((short) colNum);

// 定义单元格为字符类型,也可以指定为日期类型、数字类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 定义编码方式,为了支持中文,这里使用了ENCODING_UTF_16
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// 为单元格设置格式
cell.setCellStyle(cellStyle);

// 添加内容至单元格
cell.setCellValue("表头名-" + colNum);
}
rowNum++;
for (; rowNum < 5; rowNum++) {
//新建第rowNum行
row = sheet.createRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
//在当前行的colNum位置创建单元格
cell = row.createCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle);
cell.setCellValue("值-" + rowNum + "-" + colNum);
}
}

//合并单元格
//先创建2行5列的单元格,然后将这些单元格合并为2个大单元格
rowNum = 5;
for (; rowNum < 7; rowNum++) {
row = sheet.createRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
//在当前行的colNum位置创建单元格
cell = row.createCell((short) colNum);
}
}
//建立第一个大单元格,高度为2,宽度为2
rowNum = 5;
colNum = 0;
Region region = new Region(rowNum, (short) colNum, (rowNum + 1),(short) (colNum + 1));
sheet.addMergedRegion(region);
//获得第一个大单元格
cell = sheet.getRow(rowNum).getCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle);
cell.setCellValue("第一个大单元格");

//建立第二个大单元格,高度为2,宽度为3
colNum = 2;
region = new Region(rowNum, (short) colNum, (rowNum + 1),(short) (colNum + 2));
sheet.addMergedRegion(region);
//获得第二个大单元格
cell = sheet.getRow(rowNum).getCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle);
cell.setCellValue("第二个大单元格");

//工作薄建立完成,下面将工作薄存入文件
//新建一输出文件流
fOut = new FileOutputStream(file);
//把相应的Excel 工作簿存盘
workbook.write(fOut);
fOut.flush();
//操作结束,关闭文件
fOut.close();

System.out
.println("Excel文件生成成功!Excel文件名:" + file.getAbsolutePath());
} catch (Exception e) {
System.out.println("Excel文件" + file.getAbsolutePath() + "生成失败:" + e);
} finally {
if (fOut != null){
try {
fOut.close();
} catch (IOException e1) {
}
}
}
}

/**
* 读Excel文件内容
* @param fileName
*/
public void readExcel(String fileName) {
File file = new File(fileName);
FileInputStream in = null;
try {
//创建对Excel工作簿文件的引用
in = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(in);

//创建对工作表的引用。
//这里使用按名引用
HSSFSheet sheet = workbook.getSheet("Test_Table");
//也可用getSheetAt(int index)按索引引用,
//在Excel文档中,第一张工作表的缺省索引是0,其语句为:
//HSSFSheet sheet = workbook.getSheetAt(0);

//下面读取Excel的前5行的数据
System.out.println("下面是Excel文件" + file.getAbsolutePath() + "的内容:");
HSSFRow row = null;
HSSFCell cell = null;
int rowNum = 0;//行标
int colNum = 0;//列标
for (; rowNum < 5; rowNum++) {
//获取第rowNum行
row = sheet.getRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
// 获取当前行的colNum位置的单元格
cell = row.getCell((short) colNum);
System.out.print(cell.getStringCellValue() + "\t");
}
//换行
System.out.println();
}

in.close();
} catch (Exception e) {
System.out.println("读取Excel文件" + file.getAbsolutePath() + "失败:" + e);
} finally {
if (in != null){
try {
in.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) throws Exception {
ExcelFile excel = new ExcelFile();
String fileName = "D:\\记录明细.xls";
excel.writeExcel(fileName);
excel.readExcel(fileName);
}
}
package com.cn.gao;

import java.util.List;

public class FromExcelToDb {
public static void main(String[] args) {
//得到表格中所有的数据
List<Stu> listExcel=StuService.getAllByExcel("d://book.xls");
/*//得到数据库表中所有的数据
List<Stu> listDb=StuService.getAllByDb();*/

DBhelper db=new DBhelper();

for (Stu stuEntity : listExcel) {
int id=stuEntity.getId();
if (!StuService.isExist(id)) {
//不存在就添加
String sql="insert into student (name,sex,num) values(?,?,?)";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+""};
db.AddU(sql, str);
}else {
//存在就更新
String sql="update student set name=?,sex=?,num=? where id=?";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+"",id+""};
db.AddU(sql, str);
}
}
System.out.println("数据更7a64e58685e5aeb9363新成功!");
}
}

//从excle文档中,将值导入至list数组
//xlsPath 路径 从前台获取
//Excle导入
public List<TblUser> loadScoreInfo(String xlsPath) throws IOException{
    List temp = new ArrayList();
FileInputStream fileIn = new FileInputStream(xlsPath);
//根据指定的文件输入流导入Excel从而产生Workbook对象
Workbook wb0 = new HSSFWorkbook(fileIn);
//获取Excel文档中的第一个表单
Sheet sht0 = wb0.getSheetAt(0);
//对Sheet中的每一行进行迭代
        for (Row r : sht0) {
        //如果当前行的行号(从0开始)未达到2(第三行)则从新循环
if(r.getRowNum()<1){
continue;
}
//创建实体类
TblUser info=new TblUser();
//取出当前行第1个单元格数据,并封装在info实体stuName属性上
if(r.getCell(0)!=null){
 r.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
     info.setId(Integer.parseInt(r.getCell(0).getStringCellValue()));
}
//同上
if(r.getCell(1)!=null){
     r.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
     info.setUsername(r.getCell(1).getStringCellValue());
}
if(r.getCell(2)!=null){
     r.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
     info.setPassword(r.getCell(2).getStringCellValue());
7a686964616fe58685e5aeb9339}
if(r.getCell(3)!=null){
     r.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
     info.setState(r.getCell(3).getStringCellValue());
}
if(r.getCell(4)!=null){
     r.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
     info.setRename(r.getCell(4).getStringCellValue());
}
if(r.getCell(5)!=null){
     r.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
     info.setEmail(r.getCell(5).getStringCellValue());
}
 temp.add(info);
        }
        fileIn.close();    
        return temp;    
    }

 public void ztree()
 {
 
 }
//导出当前页的数据
public void exportPage(){
List<TblUser> list=new ArrayList<TblUser>();
String[] slist=daor.split(",");
//将页面获取到的id集合遍历,循环添加到list中,进行本页数据到导出
for (int i = 0; i < slist.length; i++) {
list.add(tus.findById(java.lang.Integer.parseInt(slist[i])));
}
tus.export(list);
}

/**
 * 导入Excle到数据库
 * @return null 不然有可能报错!
 * @throws IOException
 */

public void importExcle() throws IOException{
//调用导入文件方法并存入数组中
int s=0;//得到成功插入的条数
int i=0;//得到共有多少条
/**
 * 将不符合格式的数据错误信息存入数组中!
 * 格式要求:
 * 用户名,密码不能为空!
 * 用户名不能和已存在的用户名重复,长度在5-18位之间
 * 密码长度在6-18位之间
 */
String errors="";//保存导入失败信息
try {
System.out.println("进入方法!");

lists=this.loadScoreInfo(path);
System.out.println(path);
for (TblUser u : lists) {
i++;
if(u.getUsername()==""){
    errors+="第"+i+"条数据的用户名为空,导入失败!";//^^:分割符
    continue;
}
if(u.getPassword()==""){
errors+="第"+i+"条数据的密码为空,导入失败!";//^^:分割符
continue;
}
if(tus.findByName(u.getUsername())){
errors+="第"+i+"条数据的用户名 已存在,导入失败!";//^^:分割符
continue;
}
if(u.getUsername().length()<5 || u.getUsername().length()>20){
errors+="第"+i+"条数据的用户名格式错误,导入失败!";//^^:分割符
continue;
}
if(u.getPassword().length()<6 || u.getPassword().length()>20){
errors+="第"+i+"条数据的密码格式错误,导入失败!";//^^:分割符
continue;
}
s++;
tus.save(u);//将数组中的数据添加到数据库中!
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println("错误:"+errors);
}

        
}  

相关阅读

关键词不能为空
极力推荐
  • 怎样在单元格内换行输入?-excel换行

  • excel换行,说明:工作中每个项目有两名联系人,需要在一个单元格中输入两人姓名并换行显示。注意:在Excel的单元格中按回车并不能产生换行效果,会跳转至下一个单元格。

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