導航:首頁 > 編程語言 > javaexcel文件導入

javaexcel文件導入

發布時間:2022-08-09 19:53:26

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文件配置導入數據欄位的約束和關系。例如,主鍵、外鍵、是否允許為空等約束,通過此列對應資料庫某個表中相應的主鍵,及聯合主鍵

閱讀全文

與javaexcel文件導入相關的資料

熱點內容
如何測試流媒體伺服器的並發能力 瀏覽:159
溯源碼有分國家認證的嗎 瀏覽:218
如何通過app查詢產檢報告 瀏覽:944
拉結爾安卓手機怎麼用 瀏覽:695
驅動級進程代理源碼 瀏覽:782
androidshape畫線 瀏覽:510
程序員想辭職被拒絕 瀏覽:101
java面試邏輯 瀏覽:749
如何下載全英文app 瀏覽:724
js函數式編程指南 瀏覽:380
為什麼安卓手機相機啟動會卡 瀏覽:341
python中t是什麼意思 瀏覽:765
移動硬碟內存加密 瀏覽:407
單片機測角度 瀏覽:864
URL伺服器地址怎麼填 瀏覽:438
壓縮餅干會導致血糖高嗎 瀏覽:569
cad中xc命令怎麼用 瀏覽:424
戴爾伺服器怎麼看網卡介面 瀏覽:823
鹽鐵論pdf 瀏覽:424
最短路徑的生成演算法可用 瀏覽:457