① java 怎么把 excel文件导入到数据库
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的大单元格。
*
* @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);
}
}
② 如何用java导入excel数据到数据库
//从excle文档中,将值导入至list数组
//xlsPath路径从前台获取
//Excle导入
publicList<TblUser>loadScoreInfo(StringxlsPath)throwsIOException{
Listtemp=newArrayList();
FileInputStreamfileIn=newFileInputStream(xlsPath);
//根据指定的文件输入流导入Excel从而产生Workbook对象
Workbookwb0=newHSSFWorkbook(fileIn);
//获取Excel文档中的第一个表单
Sheetsht0=wb0.getSheetAt(0);
//对Sheet中的每一行进行迭代
for(Rowr:sht0){
//如果当前行的行号(从0开始)未达到2(第三行)则从新循环
if(r.getRowNum()<1){
continue;
}
//创建实体类
TblUserinfo=newTblUser();
//取出当前行第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());
}
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();
returntemp;
}
publicvoidztree()
{
}
//导出当前页的数据
publicvoidexportPage(){
List<TblUser>list=newArrayList<TblUser>();
String[]slist=r.split(",");
//将页面获取到的id集合遍历,循环添加到list中,进行本页数据到导出
for(inti=0;i<slist.length;i++){
list.add(tus.findById(java.lang.Integer.parseInt(slist[i])));
}
tus.export(list);
}
/**
*导入Excle到数据库
*@returnnull不然有可能报错!
*@throwsIOException
*/
publicvoidimportExcle()throwsIOException{
//调用导入文件方法并存入数组中
ints=0;//得到成功插入的条数
inti=0;//得到共有多少条
/**
*将不符合格式的数据错误信息存入数组中!
*格式要求:
*用户名,密码不能为空!
*用户名不能和已存在的用户名重复,长度在5-18位之间
*密码长度在6-18位之间
*/
Stringerrors="";//保存导入失败信息
try{
System.out.println("进入方法!");
lists=this.loadScoreInfo(path);
System.out.println(path);
for(TblUseru: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(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
System.out.println("错误:"+errors);
}
}
③ 如何在Java中导入Excel表数据
1,加入依赖的罐子文件:
引用:
*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 是多表文档,所以需要输入表索引号)
* @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");
}
}
④ 怎样将Excel文件导入数据库(在JSP环境下Java代码)
呵呵,楼主既然思路都有了还怕写不出代码么?
你这个思路没有问题的!
可以把这个问题拆分成几个小问题,就简单多了。
第一是文件上传,可以参照Jakarta的FileUpload组件,其实也不一定要用这个,用普通的Post也就行了。
第二是Excel解析,用JSL或者POI都行
第三是数据保存,这个应该简单吧,一个循环,一行对应一条数据,写好了方法循环赋值调用就行了。
第四是查询和显示,这个更简单了,不用多说。
文件上传和Excel解析的例子网上很多的,改改就变自己的了,何必在这管别人要代码呢~
⑤ 如何用java将excel中的数据导入数据
代码如下:
import java.io.*;
import jxl.*;
import jxl.write.*;
public class CreateXLS
{
public static void main(String args[])
{
try
{
//打开文件
WritableWorkbook book= Workbook.createWorkbook(new File("测试.xls"));
//生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet("第一页",0);
//在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//以及单元格内容为test
Label label=new Label(0,0,"test");
//将定义好的单元格添加到工作表中
sheet.addCell(label);
/*生成一个保存数字的单元格
必须使用Number的完整包路径,否则有语法歧义
单元格位置是第二列,第一行,值为789.123*/
jxl.write.Number number = new jxl.write.Number(1,0,789.123);
sheet.addCell(number);
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
⑥ java web 怎么导入excel文件
1.要正确的将Web客户端的Excel文件导入到服务器的数据库中,需要将客户端的Excel文件上传到服务器上。可以使用FileUpload控件完成。2.Excel文件上传到服务器指定的目录中,这里假设是该站点的upfiles目录中。3.使用SQL语句从upfiles目录中的上传Excel文件中读取数据显示或写入数据库。
⑦ java excel怎么快速导入
快速导入也是需要java的poi的,可以参照如下代码:
public List<ScoreInfo> 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;
}
//创建实体类
ScoreInfo info=new ScoreInfo();
//取出当前行第1个单元格数据,并封装在info实体stuName属性上
info.setStuName(r.getCell(0).getStringCellValue());
info.setClassName(r.getCell(1).getStringCellValue());
info.setRscore(r.getCell(2).getNumericCellValue());
info.setLscore(r.getCell(3).getNumericCellValue());
temp.add(info);
}
fileIn.close();
return temp;
}
⑧ java 中怎么从excel中导入数据
做过一个项目中EXCEL导入是纯JAVA程序写的,但是比较繁琐。自定义了一个XML文件,通过XML文件配置导入数据字段的约束和关系。例如,主键、外键、是否允许为空等约束,通过此列对应数据库某个表中相应的主键,及联合主键