A. java中excel導入怎麼實現
excel基本是xml文件的壓縮文件,思路可以是把excel文件解壓後,解析xml文件,找到你需要的xml文件中的節點和數據,導入資料庫或者畫面。樓下的POI或者xml解析器等等應該可以實現。
B. java批量導入excel
兩種方案:
1. 可以對資料庫中的這張表進行本地緩存處理,驗證時調用緩存進行匹配驗證。
2. 用程序生成需要導入excel的數據模板,在模板里將要驗證的這一列做成下拉框。此模板條件下的excel數據文件批量導入時即不用校驗。
具體採用哪種視你的應用場景來定。
C. 如何在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");
}
}
D. java 中怎麼從excel中導入數據
做過一個項目中EXCEL導入是純JAVA程序寫的,但是比較繁瑣。自定義了一個XML文件,通過XML文件配置導入數據欄位的約束和關系。例如,主鍵、外鍵、是否允許為空等約束,通過此列對應資料庫某個表中相應的主鍵,及聯合主鍵
E. 如何在Java中導入Excel表數據
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jxl.*;
public class SimUpdate {
private String fileName;
public ZfzSimUpdate(String fileName){
this.fileName = fileName;
}
static Map tNames;
static{
tNames = new HashMap();
}
/**
* 用於產生 資料庫的 ID 值,組成 [年月日時分秒(100-999)] 總共 17 位數.
* 根據不同的表名,可保證同一秒內產生的 ID 號不重復
*/
private static String getDtime() {
String rid;
Date nd = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
rid = sdf.format(nd);
return rid;
}
public String getSeqNumber(String tableName) {
if(tableName == null || "".equals(tableName))
tableName = "GENERY";
Integer it;
// noinspection SynchronizeOnNonFinalField
synchronized(tNames){
it = (Integer)tNames.get(tableName);
if(it == null){
it = new Integer(100);
tNames.put(tableName, it);
}else{
if(it.intValue() > 998)
it = new Integer(100);
else
it = new Integer(1 + it.intValue());
tNames.put(tableName, it);
}
}
return getDtime() + String.valueOf(it);
}
private void updateDb(){
try{
Connection conn = DbPool.connectDB();
if(conn != null){
Statement stmt = conn.createStatement();
/**********************************************/
jxl.Workbook rwb = null;
try{
//構建Workbook對象 只讀Workbook對象
//直接從本地文件創建Workbook
//從輸入流創建Workbook
InputStream is = new FileInputStream(fileName);
rwb = Workbook.getWorkbook(is);
//Sheet(術語:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中
//Sheet的下標是從0開始的
//獲取第一張Sheet表
Sheet rs = rwb.getSheet(0);
//獲取Sheet表中所包含的總列數
int rsColumns = rs.getColumns();
//獲取Sheet表中所包含的總行數
int rsRows = rs.getRows();
//獲取指這下單元格的對象引用
String simNumber = "",termSeqId = "";
//指定SIM卡號及序列號
for(int i=0;i<rsRows;i++){
for(int j=0;j<rsColumns;j++){
Cell cell = rs.getCell(j,i);
if(j==0){
simNumber = cell.getContents();
}
termSeqId = "633"+simNumber;
}
String sql = "查詢SQL";
int isOk = stmt.executeUpdate(sql);
if(isOk == 0 && !simNumber.equals("")){
String termId = getSeqNumber("termInf");
String insertSql = "自定義INSERT";
int isAdd = stmt.executeUpdate(insertSql);
if(isAdd > 0){
System.out.println("成功插入第"+i+"條數據");
}
}
//System.out.println("SIM卡號:"+simNumber+",序列號:"+termSeqId);
}
//以下代碼為寫入新的EXCEL,這里不使用,所以注釋
/*
//利用已經創建的Excel工作薄創建新的可寫入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("D://Book2.xls"),rwb);
//讀取第一張工作表
jxl.write.WritableSheet ws = wwb.getSheet(0);
//獲取第一個單元格對象
jxl.write.WritableCell wc = ws.getWritableCell(0, 0);
//決斷單元格的類型,做出相應的轉化
if (wc.getType() == CellType.LABEL) {
Label l = (Label) wc;
l.setString("The value has been modified.");
}
//寫入Excel對象
wwb.write();
wwb.close();
*/
}catch(Exception e){
e.printStackTrace();
}
finally{
//操作完成時,關閉對象,翻譯佔用的內存空間
rwb.close();
}
/*********************************************/
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
DbPool dbPool = new DbPool("dbConn.cfg");//連接資料庫
SimUpdate simUpdate = new SimUpdate("zfz_sim.xls");
simUpdate.updateDb();
}
}
我只用了讀取XLS,寫入沒試,應該沒問題吧,你把注釋了的拿 來試一下吧
F. java怎麼將excel表格數據導入資料庫
excel有行和列,可以對應資料庫表的行和欄位。先獲取你excel中的數據,如果你的數據是和java中實體對應的話,循環獲取每一行數據存放進實體對象中,然後進行資料庫保存就好了。
讀取excel數據可以使用poi。
G. java怎麼批量導入excel數據
兩種方案:1.可以對資料庫中的這張表進行本地緩存處理,驗證時調用緩存進行匹配驗證。2.用程序生成需要導入excel的數據模板,在模板里將要驗證的這一列做成下拉框。此模板條件下的excel數據文件批量導入時即不用校驗。具體採用哪種視你的應
H. 如何用Java將excel數據導入資料庫
我前端時間要導數據,,隨便找代碼弄了一個 能用的,貼給你看看。
public String uploadExcel(HttpServletRequest request) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
System.out.println("通過傳統方式form表單提交方式導入excel文件!");
InputStream in =null;
List<List<Object>> listob = null;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
throw new Exception("文件不存在!");
}
in = file.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
in.close();
//該處可調用service相應方法進行數據保存到資料庫中,現只對數據輸出
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
System.out.println(lo.get(0));
System.out.println(lo.get(1));
Word word = new Word();
word.setId(UUIDTools.getUUID());
word.setChinese(lo.get(1).toString());
word.setEnglish(lo.get(0).toString());
wordService.saveEnglishWord(word);
/* InfoVo vo = new InfoVo();
vo.setCode(String.valueOf(lo.get(0)));
vo.setName(String.valueOf(lo.get(1)));
vo.setDate(String.valueOf(lo.get(2)));
vo.setMoney(String.valueOf(lo.get(3)));
System.out.println("列印信息-->機構:"+vo.getCode()+" 名稱:"+vo.getName()+" 時間:"+vo.getDate()+" 資產:"+vo.getMoney()); */
}
return "result";
}
ImportExcelUtil類的getBankListByExcel方法:
public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
//創建excel工作簿
Workbook work = this.getWorkbook(in,fileName);
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍歷Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍歷當前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍歷所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
// work.close();
return list;
}
前台弄個上傳標簽 訪問這個action就行了。
I. java web 怎麼導入excel文件
1.要正確的將Web客戶端的Excel文件導入到伺服器的資料庫中,需要將客戶端的Excel文件上傳到伺服器上。可以使用FileUpload控制項完成。2.Excel文件上傳到伺服器指定的目錄中,這里假設是該站點的upfiles目錄中。3.使用SQL語句從upfiles目錄中的上傳Excel文件中讀取數據顯示或寫入資料庫。